Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detecting connected interface using c++ in linux

I want to detect which interface is now connected; and I have three 3g-modem connections and two lan connections to the server(my device didn't support wlan). I mean the type of connection is not important but the interface name and specifics is what important for me. I want to detect connected interface in my program that I wrote in c++. please tell me how to detect connected interface in c++?(root permission is not a problem.)

like image 560
Lrrr Avatar asked Dec 16 '22 12:12

Lrrr


2 Answers

Use ioctl SIOCGIFFLAGS to check is the interface UP and RUNNING:

struct ifreq ifr;

memset( &ifr, 0, sizeof(ifr) );
strcpy( ifr.ifr_name, ifrname );

if( ioctl( dummy_fd, SIOCGIFFLAGS, &ifr ) != -1 )
{
    up_and_running = (ifr.ifr_flags & ( IFF_UP | IFF_RUNNING )) == ( IFF_UP | IFF_RUNNING );
}
else
{
    // error
}

Input variable is ifrname. It should be the interface name "eth0", eth1", "ppp0" ....

Because ioctl() needs a file descriptor as parameter, you can use for example some temporary UDP socket for that:

dummy_fd = socket( AF_INET, SOCK_DGRAM, 0 );

Remember to close the socket, when not used anymore.

like image 199
SKi Avatar answered Dec 27 '22 23:12

SKi


If you are using NetworkManager, you can use it's API. You can either use the D-Bus API, the GLib wrapping, C++ Bindings for D-Bus.

If you are using Qt, you can directly use QtNetwork.

Of course, you can also go very low-level and use ioctl(7). See lsif by Adam Risi for an example.

like image 43
Michael Wild Avatar answered Dec 27 '22 23:12

Michael Wild