Check if lan device is connected using c++ in linux

I have a device on my network (wi-fi with only static IP's) with a static IP address of I use it in input for part of my code in a c++ program in linux, but if it disconnects/is powered off, the program stops responding because it tries to pull data from a non-existent location. Is there a way I can check if it disconnects so that I can stop the program before it goes out of control? Thanks for the helpful responses I know are coming!


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 );
    // 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.

See how to go very low-level and use ioctl(7). See lsif by Adam Risi for an example.

Try to ping before proceeding

int status = system("ping -c 2");  
if (-1 != status) 
    ping_ret = WEXITSTATUS(status); 

        cout<<"Ping successful"<<endl; ////Proceed 
        cout<<"Ping not successful"<<endl; ///Sleep and agin check for ping

Need Your Help

Sybase token datastream length was not correct

jdbc prepared-statement sybase

Getting below error while saving a binary into a image column.