程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C >> 關於C >> C語言+shell 實現linux網卡狀態檢測

C語言+shell 實現linux網卡狀態檢測

編輯:關於C

不解釋,直接上代碼 要求linux環境具備grep和awk(awk可選)

#include 
#include 
#include 
#include 

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;
        }
        else
        {
			fprintf(stderr, "%s: NO FOUND\r\n",if_name);
			return 0;
        }
    }

	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;
		    }
		    else
		    {
				fprintf(stderr, "%s: DOWN\r\n",if_name);
				return 1;
		    }
		}
	}

	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;
		    }
		    else
		    {
				fprintf(stderr, "%s: UNPLUGGED\r\n",if_name);
				return 2;
		    }
		}
	}

	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;
}


嵌入式編譯 mips-linux-gnu-gcc -mips32 -EL -mhard-float -Wall -o netlink netlink.c

測試結果

# ./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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved