linux c 实现网络状态检测

网上看了些帖子,按自己实际情况写了下,做个笔记。

在我系统中网卡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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值