在项目中和网络连接的模块中,要不停的去检查网络是否正常,尝试了很多的方法,最后终于找到了一个比较靠谱的方法,现在分享给大家。
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
/**********************************************************************
*函数名称:get_netlink_status
*功能描述:检测网络链接是否断开*输入参数:const char *(要检测的网口,如:eth0、eth1)*输出参数:无
*返回值:正常链接0,断开返回-1***********************************************************************/
int get_netlink_status(const char *if_name)
{
struct ifreq ifr;
int skfd = socket(AF_INET, SOCK_DGRAM, 0);
strcpy(ifr.ifr_name, if_name);
if (ioctl(skfd, SIOCGIFFLAGS, &ifr) < 0)
{
return -1;
}
if(ifr.ifr_flags & IFF_RUNNING)
return 0; // 网卡已插上网线
else return -1;
}
int main()
{
if(get_netlink_status("eth0") == 0)
printf("detect ok./n");
else
printf("detect fail./n");
}
分享到:
2012-11-14 16:32
浏览 1065
评论