`
v5browser
  • 浏览: 1137808 次
社区版块
存档分类
最新评论

Linux下检测网卡与网线连通状态

 
阅读更多

在项目中和网络连接的模块中,要不停的去检查网络是否正常,尝试了很多的方法,最后终于找到了一个比较靠谱的方法,现在分享给大家。

#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <termios.h>
#include <errno.h>
#include <string.h>
#include <android/log.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/if.h>
#include <linux/sockios.h>
#include <sys/types.h>
#include <net/if.h>

/**********************************************************************
*
函数名称: 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");
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics