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

"ip.c" 48L, 1346C                                          
#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 eth0","r"); //执行可读程序 


    if(fp == NULL)
    {
        printf("popen failure:%s\n",strerror(errno));  //显示出错原因
        return 0;
    }




    while(fgets(buf,sizeof(buf),fp)!=NULL)
    {
        if( (p1=strstr(buf,"inet addr:")) != NULL )
        {


            p2=strchr(p1,':');
            p3=strchr(p2,' ');
            memset(ipaddr,0,sizeof(ipaddr));//消除随机值 
            strncpy(ipaddr,p2+1,p3-p2);//两个指针相减得到中间元素 
            printf("p3-p2-1=%d\n",p3-p2-1);
            printf("p3-p2=%d\n",p3-p2);
      #if 1
            printf("IP address:%s\n",ipaddr);//  
            printf("p2: %s",p2);
            printf("p3: %s",p3);
      #endif
            p2=strrchr(p1,':');
            p3=strrchr(p2,'\n');
            memset(netmask,0,sizeof(netmask));
            strncpy(netmask,p2+1,p3-p2);
            printf("Netmask address:%s\n",netmask);
       }
   }


   pclose(fp);
   return 0;
}


图一为eth1的情况,输出不了
图2为ethod的情况,不同的系统要求不一样






猜你喜欢

转载自blog.csdn.net/adteam_/article/details/79179001