Created
June 19, 2021 15:52
-
-
Save Nikhiladiga/d8b9ed4f51a9401e3f4b39601265b7fe to your computer and use it in GitHub Desktop.
Get UP/DOWN status of network interface in Linux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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(ðreq, 0, sizeof(ethreq)); | |
strncpy(ethreq.ifr_name, interface.c_str(), IFNAMSIZ); | |
int res = ioctl(fd, SIOCGIFFLAGS, ðreq); | |
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