Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if interface is up

Tags:

c++

linux

ioctl

Title pretty much says it all. If I run ifconfig, I get this:

eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
    inet -snip-  netmask 255.255.255.0  broadcast -snip-
    ...

Using this, I can know if it's up or not (<UP,...), but I want to be able to do this in C (or C++, if there is a simpler solution there) without relying on parsing external processes.


Here is what I've got so far (doesn't work):

bool is_interface_online(std::string interface) {
    struct ifreq ifr;
    int sock = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
    memset(&ifr, 0, sizeof(ifr));
    strcpy(ifr.ifr_name, interface.c_str());
    if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) {
            perror("SIOCGIFFLAGS");
    }
    close(sock);
    return !!(ifr.ifr_flags | IFF_UP);
}

Can anyone point me in the correct direction for this?

like image 783
MiJyn Avatar asked Mar 30 '13 20:03

MiJyn


2 Answers

Answer was simple: I used the bitwise OR (|) operator instead of the AND (&) operator. Fixed code is:

bool is_interface_online(std::string interface) {
    struct ifreq ifr;
    int sock = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
    memset(&ifr, 0, sizeof(ifr));
    strcpy(ifr.ifr_name, interface.c_str());
    if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) {
            perror("SIOCGIFFLAGS");
    }
    close(sock);
    return !!(ifr.ifr_flags & IFF_UP);
}
like image 129
MiJyn Avatar answered Oct 14 '22 22:10

MiJyn


If you care about the up/down state of the interface you might want to use the "IFF_RUNNING" flag instead of the "IFF_UP" flag provided by the current answer.

like image 25
invapid Avatar answered Oct 14 '22 22:10

invapid