文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>得到本机IP地址

得到本机IP地址

时间:2007-05-10  来源:白石

得到本机IP地址

  方法1:通过域名得到------目标板没有域名,无法取得  

void print_ip_lst()
{
  static char ip[32];
  struct hostent *hp;
  struct in_addr in;
  int id=0;
  char hostname[32];

  gethostname(hostname,31);

  printf("hostname = %s\n",hostname);

  *ip=0;
  if((hp=gethostbyname(hostname))==NULL)
  {
    printf("ERROR: unable get host '%s' ip\n",hostname);
    return;
  }

  while(hp->h_addr_list[id]!=NULL)
  {
    memcpy(&in.s_addr,hp->h_addr_list[id],sizeof(in.s_addr));
    strcpy(ip,inet_ntoa(in));
    printf("ip is %s\n",ip);
    id++;
  }
}

 

方法2:ioctl------已验证

#include <sys/ioctl.h>
#include <net/if.h>

int get_ip_address_r1(char *ip, char *netmask)
{
 struct ifreq ifr;
 //struct ifconf ifc;

 int sockfd = socket(AF_INET,SOCK_DGRAM,0);
 strcpy(ifr.ifr_ifrn.ifrn_name,"eth0");
 //strcpy(ifr.ifr_ifrn.ifrn_name,"lo");

 ioctl(sockfd, SIOCGIFFLAGS, &ifr);
 if ((ifr.ifr_flags & 0x01) == 0)
 {
  close(sockfd);
  return -1;
 }
 ioctl(sockfd, SIOCGIFADDR, &ifr);
 strcpy(ip, inet_ntoa(((struct sockaddr_in*)&ifr.ifr_addr)->sin_addr));
 //printf("ip = %s\n",ip);

 ioctl(sockfd, SIOCGIFNETMASK,&ifr);
 strcpy(netmask, inet_ntoa(((struct sockaddr_in*)&ifr.ifr_netmask)->sin_addr));
 //printf("netmask = %s\n",netmask);

 close(sockfd);
 return 0;
}

方法3:通过shell------在目标板上,system("ifconfig eth0 >/var/ip");ip文件为空,原因不明。

void print_ip_lst( char *ip)
{
    char buf[1024];
    FILE *fp=NULL;
    int nCount;
    char *pStr=buf;
    char *pStr1;

//    sprintf(buf,"ifconfig eth0 >%s",TEMPFILE_IP);

//    system(buf);

    system("ifconfig eth0 >/var/ip");
    
    fp = fopen(TEMPFILE_IP,"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," ");
        snprintf(ip,(int)pStr1-(int)pStr-10,"%s",pStr+10);
        printf("ip=%s\n",ip);
    }
    fclose(fp);
}

相关阅读 更多 +
排行榜 更多 +
拉力竞速2

拉力竞速2

体育竞技 下载
文字乱舞水浒

文字乱舞水浒

角色扮演 下载
蓝图公考

蓝图公考

学习教育 下载