如何检测网线是否插好

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

//AUTHOR: lanyang123456

//DATE: 2014-10-22

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



/*
检测物理连接是否正常
detect phy link
cable 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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值