dbusgdbus

C++ library for receiving network interface up/down notification with interface name on Ubuntu


This post has two questions. 1. network interface up/down notification on a specific network device 2. list the network devices.

See below for the answers provided by me. (Thanks to Velkan for helping me in arriving at this)

I am looking for a c++ library which receives the network interface up/down event notification with interface name on Ubuntu machine. I have been asked by my colleagues to use dbus interfaces for the same. Used the link below for the same, which just notifies about any interface up/down event without interface name.

https://cgit.freedesktop.org/NetworkManager/NetworkManager/tree/examples/C/glib/monitor-nm-state-gdbus.c

I am googling around for a quite sometime now, I could not find right examples and even the dbus documentation is not straight forward or not providing the information what I am looking for.

Any help on this would be greatly helpful.

Thanks in Advance


Solution

  • Anyone who wants a working code sample, can replace similar line given below, in the link shared in the question (https://cgit.freedesktop.org/NetworkManager/NetworkManager/tree/examples/C/glib/monitor-nm-state-gdbus.c).

    Code snippet for listening up/down event on a specific device Here I have just changed the object path parm value to

    Code snippet for list the devices available.

    proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM,
                                           flags,
                                           NULL, /* GDBusInterfaceInfo */
                                           "org.freedesktop.NetworkManager",
                                           "/org/freedesktop/NetworkManager",
                                           "org.freedesktop.NetworkManager",
                                           NULL, /* GCancellable */
                                           &error);
    
    ret = g_dbus_proxy_call_sync (proxy,
                                  "GetDevices",
                                  NULL,
                                  G_DBUS_CALL_FLAGS_NONE, -1,
                                  NULL, &error);
    if (!ret) {
        g_dbus_error_strip_remote_error (error);
        g_print ("ListConnections failed: %s\n", error->message);
        g_error_free (error);
        return;
    }
    
    g_variant_get (ret, "(^ao)", &paths);
    g_variant_unref (ret);
    
    for (i = 0; paths[i]; i++)
        g_print ("%s\n", paths[i]);
    

    Output for list of network devices (I have 2 nic cards in my machine)

    /org/freedesktop/NetworkManager/Devices/0

    /org/freedesktop/NetworkManager/Devices/1