ifconfig eth1是在我电脑上的普通网卡设备,今天我们来对这几行数字进行操作,从而读取它的IP地址和子网掩码Netmask
[lingyun@localhost 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
[lingyun@localhost 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;
}
接下来是执行程序:
[lingyun@localhost file]$ gcc popen.c
[lingyun@localhost 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
[lingyun@localhost file]$