C語言+shell實現(xiàn)linux網卡狀態(tài)檢測
更新時間:2018年06月29日 10:04:47 作者:handyhuang
這篇文章主要為大家詳細介紹了C語言+shell實現(xiàn)linux網卡狀態(tài)檢測,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了C語言+shell實現(xiàn)linux網卡狀態(tài)檢測的具體代碼,供大家參考,具體內容如下
不解釋,直接上代碼 要求linux環(huán)境具備grep和awk(awk可選)
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
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 <ethname>", 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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
關于C++智能指針shared_ptr和unique_ptr能否互轉問題
C++中的智能指針最常用的是shared_ptr和unique_ptr,C++新手最常問的問題是我從一個函數(shù)中拿到unique_ptr,但要轉成shared_ptr才能使用,要怎么轉換?同理是否能將shared_ptr轉換成unique_ptr,面對這些問題,跟隨小編一起看看吧2022-05-05
使用C++和Direct3D (d3d)獲取屏幕截圖并根據(jù)傳入分辨率進行縮放圖片大小(最新推薦)
這篇文章主要介紹了使用C++和Direct3D (d3d)獲取屏幕截圖并根據(jù)傳入分辨率進行縮放圖片大小,本文給大家講解的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04
strings命令分析淺談Go和C++編譯時的一點小區(qū)別
今天小編就為大家分享一篇關于strings命令分析淺談Go和C++編譯時的一點小區(qū)別,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-04-04

