linux下得到本机IP地址

来源:互联网 发布:余罪用什么软件看 编辑:程序博客网 时间:2024/05/14 16:46

通过调用system()函数,首先确定你要root权限,这样才能运行ifconfig

#include<stdio.h>
#include <stdlib.h>
#include<string.h>
int get_ip(char *ip)
{

  char buf[1024];
  FILE *fp=NULL;
  int nCount;
  char *pStr=buf;
  char *pStr1;
   int ret = -1;


system("ifconfig eth0 >/tmp/tmpip");
fp = fopen("/tmp/tmpip","r");
while(1)
{
    nCount = fread(pStr,sizeof(char),1024,fp);
    pStr += nCount;
    if(feof(fp))
    {

        break;
    }
}
if((pStr=strstr(buf,"inet addr:"))!=NULL)
{
    pStr1 = strstr(pStr+10," ");

    snprintf(ip,(int)pStr1-(int)pStr-9,"%s",pStr+10);
    printf("/nip=======[%s]/n/n",ip);
    ret = 0;
}
else
{
    ret = -1;
    goto error;
}

error:
fclose(fp);
system("rm /tmp/tmpip");
return ret;

}

 

 

本文参考:http://blog.chinaunix.net/u/29845/showart_297151.html

原创粉丝点击