gethostbyname返回ip地址127.0.0.1

时间:2015-01-23 18:57:59

标签: c linux networking

我想通过以下代码片段获取当前系统的IP地址:

if(gethostname(src_host, sizeof(src_host)) < 0)  {
    printf("Error in getting host name...\n");
    return 0;
}   else    {
    printf("Host name = %s\n", src_host);
    if((src_hst = gethostbyname(src_host)) == NULL) {
        printf("Cannot resolve host...\n");
        return 0;
    }else   {
        ip->ip_src = (*(struct in_addr *)src_hst->h_addr_list[0]);
        printf("Ip Address=%s\n", inet_ntoa(ip->ip_src));
    }

}

但是在输出中我得到的是12.0.0.1,这是本地IP地址(我是networing的新手)我想在eth0中定义172.23.1.182。

有人可以帮忙吗?

lovebird@lovebird:~/prog/icmp$ ifconfig
eth0      Link encap:Ethernet  HWaddr 60:eb:69:71:7f:c0  
          inet addr:172.23.1.182  Bcast:172.23.255.255  Mask:255.255.0.0
          inet6 addr: fe80::62eb:69ff:fe71:7fc0/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1831227 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1362960 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:1549696322 (1.5 GB)  TX bytes:296632333 (296.6 MB)

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:9757 errors:0 dropped:0 overruns:0 frame:0
          TX packets:9757 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:944058 (944.0 KB)  TX bytes:944058 (944.0 KB)

wlan0     Link encap:Ethernet  HWaddr 70:f3:95:b4:23:69  
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

2 个答案:

答案 0 :(得分:1)

使用getifaddrs将返回分配给该接口的地址。 gethostname基本上是一个DNS请求,由/etc/hosts文件中的条目提供。

答案 1 :(得分:0)

我有类似的情况。 我的/ etc / hosts文件包含Dell-Laptop的以下条目:

127.0.1.1   Dell-Laptop
192.168.1.8 Dell-Laptop # Tony's Dell Inspiron Laptop

代码的一个小mod将同时获得:

if(gethostname(src_host, sizeof(src_host)) < 0)  {
    printf("Error in getting host name...\n");
    return 0;
}   else    {
    printf("Host name = %s\n", src_host);
    if((src_hst = gethostbyname(src_host)) == NULL) {
        printf("Cannot resolve host...\n");
        return 0;
    }else   {
        // ip->ip_src = (*(struct in_addr *)src_hst->h_addr_list[0]);
        // printf("Ip Address=%s\n", inet_ntoa(ip->ip_src));
        for(idx=0;src_hst->h_addr_list[idx];idx++)
        {
            printf("Ip Address=%s\n", 
             inet_ntoa((*(struct in_addr *)src_hst->h_addr_list[idx])));
        }
    }

}