Linux下检测以太网链路状态代码

该方法用到了ioctl操作ETHTOOL,需要root权限, 否则会失败!

 

 //  PARAM: devname -- just the device name such as eth0, eth1 etc.
//   RETURN: -1 -- error , details can check errno
//           1  -- interface link up
//           0  -- interface link down.
int link_status(const char* devname)
{
    int      ret = 1;
    int      fd;
    struct ifreq ifr;
    struct ethtool_value edata;

    edata.cmd = ETHTOOL_GLINK;
    edata.data = 0;
    memset(&ifr, 0, sizeof(ifr));
    snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", devname);
    ifr.ifr_data = (char *) &edata;
    if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
        fprintf(stderr, "socket() error: %s\n", strerror(errno));
        ret = -1;
        goto done;
    }

    if (ioctl(fd, SIOCETHTOOL, &ifr) == -1) {
        fprintf(stderr, "ioctl() SIOCETHTOOL error: %s\n", strerror(errno));
        ret = -1;
        
        goto done;
    }

    ret = (edata.data > 0 ? 1 : 0);

done:
    if (fd > 0) close(fd);
    return ret;
}


 

 

你可能感兴趣的:(linux,socket,struct,interface)