写一个函数,获取某张网卡的IP地址

写一个函数,获取某张网卡的IP地址,函数原型为:
 int get_ipaddr(char *intf, char *ipaddr)
返回值: 0表示成功, -1表示失败
输入参数:  intf这是网卡的名字,譬如第一张网卡传参为"eth0"
输出参数: ipaddr是返回的IP地址放到这个buf里,注意不要溢出;

程序设计提示:
1, 使用pipe创建一个管道,并使用fork()创建一个子进程;
2, 父进程关闭管道的写端,子进程关闭管道的读端(思考为什么?)
3, 子进程重定向标准输出为管道的写端(想想上一次布置的任务怎么做重定向)
4, 子进程执行ifconfig eth0命令,这时命令的输出将会输出到到管道上;
5, 父进程从管道里读取字符串,并用字符串解析函数获取到IP地址;

 

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<string.h>

#define BUF_SIZE 1000
#define IP_ADDR_LEN 20

int get_ipaddr(char *intf,char *ipaddr)
{
    int pipe_fd[2];
    pid_t pid;
    char r_buf[BUF_SIZE];
    char w_buf[BUF_SIZE];
    char *buf1,*buf2,*buf3;
    if(pipe(pipe_fd) < 0)
    {
        printf("pipe create error\n");
        return -1;
    }

    if((pid=fork()) <  0)
    {
        printf("fork error \n");
        return -1;
    }

    if (pid > 0)
    {
        close(pipe_fd[1]);
        sleep(1);
        read(pipe_fd[0],r_buf,BUF_SIZE);

        if((buf1 = strstr(r_buf,intf)) == NULL)
         {
             printf("no found %s \n",intf);
             return -1;
         }


        buf2 = strstr(buf1,"inet addr");

        buf3 = strchr(buf2,':');
        buf3++;

        while(*buf3 !=' ')
        {
            *ipaddr++ = *buf3++;
        }
        *ipaddr = '\0';
        close(pipe_fd[0]);

    }
    else if(pid == 0)
    {
       close(pipe_fd[0]);
       dup2(pipe_fd[1],1);
       system("ifconfig");
       close(pipe_fd[1]);
    }
    return 0;
}
void main()
{
     char ipaddr[IP_ADDR_LEN];
     get_ipaddr("eth0",ipaddr);
     printf("ipaddr:%s\n",ipaddr);
 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值