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.)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With