该方法用到了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;
}


 

 

GitHub 加速计划 / li / linux-dash
10.39 K
1.2 K
下载
A beautiful web dashboard for Linux
最近提交(Master分支:23 天前 )
186a802e added ecosystem file for PM2 4 年前
5def40a3 Add host customization support for the NodeJS version 4 年前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐