如何检测网线是否插好

来源:互联网 发布:linq实战源码 编辑:程序博客网 时间:2024/04/30 15:49

//----------------------------------------------------

//AUTHOR: lanyang123456

//DATE: 2014-10-22

//----------------------------------------------------



/*检测物理连接是否正常detect phy linkcable connected or disconnected.*/#include <sys/types.h>          /* See NOTES */#include <sys/socket.h>#include <stdio.h>#include <sys/ioctl.h>#include <net/if.h>#include <linux/ethtool.h>#include <linux/sockios.h>#include <errno.h>#include <string.h>int detect_ethtool(int skfd, const char *ifname){        struct ifreq ifr;        struct ethtool_value edata;        memset(&ifr, 0, sizeof(ifr));        edata.cmd = ETHTOOL_GLINK;        strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name)-1);        ifr.ifr_data = (char *) &edata;        if (ioctl(skfd, SIOCETHTOOL, &ifr) == -1)        {                printf("ETHTOOL_GLINK failed: %s\n", strerror(errno));                return -1;        }        return edata.data;}int main(){int fd;int ret;const char *interface = "eth0";fd = socket(AF_INET, SOCK_STREAM, 0);if (fd < 0) {perror("socket() error.\n");return -1;}ret = detect_ethtool(fd, interface);if (ret < 0) {perror("detect cable link state failed.\n");return -1;} else if (ret == 0) {printf("link state: cable disconnected.\n");} else if (ret == 1) {printf("link state: cable connected.\n");}return 0;}

参考

http://www.cppblog.com/bobocpp/archive/2009/02/21/74475.aspx
http://blog.csdn.net/evenness/article/details/7665970
http://blog.chinaunix.net/uid-7190071-id-2677708.html



0 0
原创粉丝点击