How to check Ethernet in Linux?

后端 未结 5 718
-上瘾入骨i
-上瘾入骨i 2020-12-06 07:26

I need the test case for Ethernet in Linux using C code to check eth0. If eth0 is down, we enable the net then check if up and the test is passed.<

5条回答
  •  天命终不由人
    2020-12-06 08:03

    To check if the link is up, try something like this. It works without root privileges.

    #include         // printf
    #include        // strncpy
    //#include  // AF_INET
    #include     // SIOCGIFFLAGS
    #include         // errno
    #include    // IPPROTO_IP
    #include        // IFF_*, ifreq
    
    #define ERROR(fmt, ...) do { printf(fmt, __VA_ARGS__); return -1; } while(0)
    
    int CheckLink(char *ifname) {
        int state = -1;
        int socId = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
        if (socId < 0) ERROR("Socket failed. Errno = %d\n", errno);
    
        struct ifreq if_req;
        (void) strncpy(if_req.ifr_name, ifname, sizeof(if_req.ifr_name));
        int rv = ioctl(socId, SIOCGIFFLAGS, &if_req);
        close(socId);
    
        if ( rv == -1) ERROR("Ioctl failed. Errno = %d\n", errno);
    
        return (if_req.ifr_flags & IFF_UP) && (if_req.ifr_flags & IFF_RUNNING);
    }
    
    int main() {
        printf("%d\n", CheckLink("eth0"));
    }
    

    If IFF_UP is set, it means interface is up (see ifup). If IFF_RUNNING is set then interface is plugged. I also tried using the ethtool ioctl call, but it failed when the gid was not root. But just for the log:

    ...
    #include      // __u32
    #include  // ETHTOOL_GLINK
    #include  // SIOCETHTOOL
    ...
    int CheckLink(char *ifname) {
        ...
        struct ifreq if_req;
        (void) strncpy( if_req.ifr_name, ifname, sizeof(if_req.ifr_name) );
    
        struct ethtool_value edata;
        edata.cmd = ETHTOOL_GLINK;
        if_req.ifr_data = (char*) &edata;
    
        int rv = ioctl(socId, SIOCETHTOOL, &if_req);
        ...
    
        return !!edata.data;
    }
    

提交回复
热议问题