【发布时间】:2015-01-23 18:57:58
【问题描述】:
我想通过下面的代码sn-p得到我当前系统的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 地址(我是网络新手)我想要在 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)
【问题讨论】:
-
您使用的是哪个主机字符串?您是否尝试过遍历所有返回的地址?
-
检查您的
/etc/hosts文件。 -
虽然传统上机器自己的主机名和地址是其
/etc/hosts中的第一个条目,但已经有很长时间没有安全的假设了。现在,机器自己的主机名根本不一定记录在/etc/hosts中。
标签: c linux networking