Linux下监测网卡状态
Posted smartvxworks
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linux下监测网卡状态相关的知识,希望对你有一定的参考价值。
目录
1.说明
此代码主要对Linux下网卡4种状态进行检测,可以检查:
- 网卡是否存在;
- 网卡是否down;
- 网卡UP,插了网线(RUNNING);
- 网卡UP,没有插网线
2.解析命令法:
2.1.CODE
#define BUFSIZ 256
/*check if_name status
*if not exist,return 0
*if exist and down,return 1
*if up and notlink,return 2
*if up and link, return 3
*/
int get_if_status(char *if_name)
char buffer[BUFSIZ];
char cmd[100];
FILE *read_fp;
int chars_read;
int ret =0;
memset( buffer, 0, BUFSIZ );
memset( cmd, 0, 100 );
sprintf(cmd, "ifconfig -a | grep %s",if_name);
read_fp = popen(cmd, "r");
if ( read_fp != NULL )
chars_read = fread(buffer, sizeof(char), BUFSIZ-1, read_fp);
pclose(read_fp);
if (chars_read > 0)
ret = 1; /*if_name exist*/
else
fprintf(stderr, "%s: NO FOUND\\r\\n",if_name);
return 0; /*if_name not exist*/
if(ret == 1)
memset( buffer, 0, BUFSIZ );
memset( cmd, 0, 100 );
sprintf(cmd, "ifconfig | grep %s",if_name);
read_fp = popen(cmd, "r");
if ( read_fp != NULL )
chars_read = fread(buffer, sizeof(char), BUFSIZ-1, read_fp);
pclose(read_fp);
if (chars_read > 0)
ret = 2; /*if_name exist and up*/
else
fprintf(stderr, "%s: DOWN\\r\\n",if_name);
return 1; /*if_name exist but down*/
if(ret == 2)
memset( buffer, 0, BUFSIZ );
memset( cmd, 0, 100 );
sprintf(cmd, "ifconfig %s | grep RUNNING | awk 'print $3'",if_name);
read_fp = popen(cmd, "r");
if ( read_fp != NULL )
chars_read = fread(buffer, sizeof(char), BUFSIZ-1, read_fp);
pclose(read_fp);
if (chars_read > 0)
fprintf(stderr, "%s: LINKED\\r\\n",if_name);
return 3; /*if_name up and link*/
else
fprintf(stderr, "%s: UNPLUGGED\\r\\n",if_name);
return 2; /*if_name up and notlink*/
return -1;
int main(int argc, char* argv[])
int i=0;
if(argc != 2)
fprintf(stderr, "usage: %s ", argv[0]);
return -1;
i = get_if_status(argv[1]);
printf( "if_status = %d\\n", i );
return 0;
2.2.TEST
# ./netlink eth100
eth100: NO FOUND
if_status = 0
#
# ifconfig eth0 down
# ./netlink eth0
eth0: DOWN
if_status = 1
#
# ifconfig eth0 up
# ./netlink eth0
eth0: UNPLUGGED
if_status = 2
#
# ./netlink eth0
eth0: LINKED
if_status = 3
3.SOCKET法
是通过socket解析网卡当前状态,来判断网卡是否存在。
实际实现过程是通过socket获取网卡的SIOCGIFFLAGS属性,判断其IFF_UP属性即可。
SIOCGIFFLAGS属性:
以上是关于Linux下监测网卡状态的主要内容,如果未能解决你的问题,请参考以下文章
怎么在linux 系统下,禁用和启用网卡,并看状态,比如像WINDOW XP 下 本地连接,禁用,启用,连接状态,