利用popen写一个函数获取某一张指定的网卡的IP地址

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]$ 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

姜亚轲

你花钱的样子真帅

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值