利用popen寫一個函式獲取某一張指定的網絡卡的IP地址
阿新 • • 發佈:2019-02-02
ifconfig eth1是在我電腦上的普通網絡卡裝置,今天我們來對這幾行數字進行操作,從而讀取它的IP地址和子網掩碼Netmask
[[email protected] file]$ ifconfig eth1
eth1 Link encap:Ethernet HWaddr 00:0C:29:27:74:4B
inet addr:192.168.242.129 Bcast:192.168.242.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe27:744b/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:31527 errors:0 dropped:0 overruns:0 frame:0
TX packets:24552 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:11397306 (10.8 MiB) TX bytes:3406468 (3.2 MiB)
Interrupt:19 Base address:0x2024
[ [email protected] file]$
程式如下:
#include <ctype.h> #include <stdio.h> #include <errno.h> #include <string.h> int main(int argc,char **argv) { FILE *fp; char buf[512]; char *p1,*p2,*p3; char ipaddr[16]; char netmask[16]; fp=popen("ifconfig eth1","r"); /*popen()用於建立一個管道,內部實現為呼叫fork 產生一個子程序,執行一個shell以執行命令來開啟一個程序*/ if(fp == NULL) { printf("popen failure:%s\n",strerror(errno)); /*如果開啟失敗則列印錯誤資訊*/ return 0; } while(fgets(buf,sizeof(buf),fp)!=NULL) /*fgets從檔案中按行讀取資料*/ { if( (p1=strstr(buf,"inet addr:")) != NULL ) /*strstr查詢字串第一次出現的位置*/ { printf("buf:%s\n",buf); p2=strchr(p1,':'); /*strchr查詢字元第一次出現的位置*/ p3=strchr(p2,' '); #if 0 /*如果有必要,可以列印p2,p3所指向的值/ printf("p2:%s\n",p2); printf("p3:%s\n",p3); #endif memset(ipaddr,0,sizeof(ipaddr)); /*用之前先用memset清空,後同*/ strncpy(ipaddr,p2+1,p3-1-p2); /*strncpy字串拷貝,注意每個指標地址*/ printf("IP address:%s\n",ipaddr); p2=strrchr(p1,':'); /*strrchr查詢字元最後一次出現的位置*/ p3=strrchr(p2,'\n'); #if 0 printf("p2:%s\n",p2); printf("p3:%s\n",p3); #endif memset(netmask,0,sizeof(netmask)); strncpy(netmask,p2+1,p3-1-p2); printf("Netmask address:%s\n",netmask); } } pclose(fp); /*popen必須由pclose關閉*/ return 0; }
接下來是執行程式:
[[email protected] file]$ gcc popen.c
[[email protected] file]$ ./a.out
buf: inet addr:192.168.242.129 Bcast:192.168.242.255 Mask:255.255.255.0
IP address:192.168.242.129
Netmask address:255.255.255.0
[[email protected] file]$