//----------------------------------------------------
//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