网上看了些帖子,按自己实际情况写了下,做个笔记。
在我系统中网卡eth0 目录如下:
检测网络状态是可以根据里面的配置值:up 或down 判断网卡是否启用。
源码贴出如下:
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int connect_check()
{
int net_fd;
char statue[20];
net_fd=open("/sys/class/net/eth0/operstate",O_RDONLY);//以只读的方式打开/sys/class/net/eth0/operstate
if(net_fd<0)
{
printf("open err\n");
return 0;
}
printf("open success\n");
memset(statue,0,sizeof(statue));
int ret=read(net_fd,statue,10);
printf("statue is %s",statue);
if(NULL!=strstr(statue,"up"))
{
printf("on line\n");
return 0;
}
else if(NULL!=strstr(statue,"down"))
{
printf("off line\n");
return 0;
}
else
{
printf("unknown err\n");
return 0;
}
}
int main(int argc,char*argv[])
{
connect_check();
return 0;
}