Skip to content

Instantly share code, notes, and snippets.

@Nikhiladiga
Created June 19, 2021 15:52
Show Gist options
  • Save Nikhiladiga/d8b9ed4f51a9401e3f4b39601265b7fe to your computer and use it in GitHub Desktop.
Save Nikhiladiga/d8b9ed4f51a9401e3f4b39601265b7fe to your computer and use it in GitHub Desktop.
Get UP/DOWN status of network interface in Linux
#include <iostream>
#include <netinet/in.h>
#include <string.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <unistd.h>
int is_interface_online(std::string interface)
{
int fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd < 0)
{
return -1;
}
struct ifreq ethreq;
memset(&ethreq, 0, sizeof(ethreq));
strncpy(ethreq.ifr_name, interface.c_str(), IFNAMSIZ);
int res = ioctl(fd, SIOCGIFFLAGS, &ethreq);
if (res < 0)
{
return res;
}
if (ethreq.ifr_flags & IFF_RUNNING)
{
close(fd);
return 0;
}
close(fd);
return 1;
}
int main(int argc, char *argv[])
{
int result = is_interface_online(argv[1]);
if (result == 0)
{
std::cout << "TRUE\n";
}
else
{
std::cout << "FALSE\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment