分类: LINUX
2014-10-18 12:08:28
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "mylib.h"
/*================================================================
本程序判断网线是否断开
调用例子:
struct ifreq ifr;
memset(&ifr , 0 , sizeof(ifr));
strcpy(ifr.ifr_name, "eth0");
if(0 == do_gset(&ifr))
{
printf("link detected : yes\n");
}
else
{
printf("link detected : no\n");
}
如果socket失败返回-1 同时有socket错误提示
如果获取不到信息 会有提示信息同事返回-1
如果成功则返回0
===============================================================*/
int do_gset(struct ifreq *ifr)
{
int err;
int fd;
int allfail = 1;
struct ethtool_value edata;
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("socket");
return -1;
}
//fprintf(stdout, "Settings for %s:\n", devname);
edata.cmd = ETHTOOL_GLINK;
ifr->ifr_data = (caddr_t)&edata;
err = ioctl(fd, SIOCETHTOOL, ifr);
if (err == 0)
{
if(edata.data)
{
return 0;
}
else
{
return -1;
}
//fprintf(stdout , " Link detected: %s\n" , edata.data ? "yes":"no");
}
else if (errno != EOPNOTSUPP)
{
perror("Cannot get link status");
close(fd);
return -1;
}
}
/*==============================================================
本程序判断网卡是否开启
调用例子:
i = get_netlink_status("eth0");
if(0 == i)
{
printf("UP\n");
}
else if(-1 == i)
{
printf("socket fail\n");
}
else
{
printf("DOWN\n");
}
}
返回-1 socket失败
返回-2 说明网卡没有开
返回0 网卡开了
==============================================================*/
int get_netlink_status(char* devname)
{
int ret;
int sd;
struct ifreq ifr;
memset(&ifr , 0 , sizeof(ifr));
strcpy(ifr.ifr_name, devname);
sd = socket(AF_INET , SOCK_DGRAM , 0);
if(sd < 0)
{
perror("socket");
return -1;
}
ret = ioctl(sd , SIOCGIFFLAGS , &ifr);
if((ifr.ifr_flags) & IFF_UP)
{
return 0;
}
else
{
return -2;
}
}
转载自:http://zhenyaliu.blog.163.com/blog/static/2377571920107251158565/