int get_ipaddr(char *intf, char *ipaddr)
返回值: 0表示成功, -1表示失败
输入参数: intf这是网卡的名字,譬如第一张网卡传参为"eth0"
程序设计:
1, 使用pipe创建一个管道,并使用fork()创建一个子进程;
2, 父进程关闭管道的写端,子进程关闭管道的读端
3, 子进程重定向标准输出为管道的写端
4, 子进程执行ifconfig命令,这时命令的输出将会输出到到管道上;
5, 父进程从管道里读取字符串,并用字符串解析函数获取到IP地址;
在命令行中输入"ifconfig"命令可以获取网卡的信息,要从这些信息中获取IP地址,就必须要找到“inet addr”这一行,找到这一行后发现第一个冒号的后面就是IP地址,IP地址的后面是空格作为分隔符。
[zhouyou@centos6 test]$ ifconfig
eth0 Link encap:Ethernet HWaddr 50:E5:49:83:76:1C
inet addr:192.168.1.2 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::52e5:49ff:fe83:761c/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1764477 errors:0 dropped:0 overruns:0 frame:0
TX packets:1034434 errors:0 dropped:0 overruns:0 carrier:3
collisions:0 txqueuelen:1000
RX bytes:460219393 (438.8 MiB) TX bytes:518171749 (494.1 MiB)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:4220587 errors:0 dropped:0 overruns:0 frame:0
TX packets:4220587 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:35475823836 (33.0 GiB) TX bytes:35475823836 (33.0 GiB)
程序如下:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUF_SIZE 512
#define IP_ADDR_LEN 20
int get_ipaddr(char *intf,char *ipaddr)
{
int fd[2];
char buf[BUF_SIZE];
char *buf1,*buf2,*buf3;
pid_t pid;
if(pipe(fd) < 0)
{
printf("pipe error\n");
return -1;
}
if((pid = fork()) < 0)
{
printf("fork error\n");
return -1;
}
else if(pid > 0)
{
close(fd[1]);
read(fd[0],buf,BUF_SIZE);
if((buf1=strstr(buf,intf)) == NULL)
{
printf("not found\n");
return -1;
}
if((buf2=strstr(buf1,"inet addr")) == NULL)
{
printf("not found\n");
return -1;
}
buf3=strchr(buf2,':');
++buf3;
while(*buf3!=' ')
{
*ipaddr++ = *buf3++;
}
*ipaddr='\0';
close(fd[0]);
}
else
{
close(fd[0]);
dup2(fd[1],1);
system("ifconfig");
close(fd[1]);
}
return 0;
}
void main()
{
char ipaddr[IP_ADDR_LEN];
get_ipaddr("eth0",ipaddr);
printf("%s\n",ipaddr);
}