如何在C中获取我的非环回网络ip地址? [英] How to get my non-loopback network ip address in C?
问题描述
要在两个主机之间进行通信,我需要将主机的IP地址发送到另一个站点.问题是,如果我请求我的IP地址,可能是我找回了本地环回IP地址(127.x.x.x),而不是网络(以太网)IP地址.
For a communication between two hosts, I need to send the IP address of my host to the other site. The problem is that if I request my IP address, it might be that I get back my local loopback IP addres (127.x.x.x) , not the network (ethernet) IP address.
我使用以下代码:
char myhostname[32];
gethostname(myhostname, 32);
hp = gethostbyname(myhostname);
unsigned my_ip = *(unsigned*)(hp->h_addr);
if( (my_ip % 256) == 127) {
/* Wrong IP adress as it's 127.x.x.x */
printf("Error, local IP address!");
return;
}
解决此问题的唯一方法是确保/etc/hosts中的主机名位于真实的网络地址后面,而不是本地环回(例如Ubuntu的默认值).
The only way to solve it is to make sure my hostname in /etc/hosts is behind the real network address, not the local loopback (the default for e.g. Ubuntu).
有没有一种方法可以不依赖于/etc/hosts的内容来解决此问题?
Is there a way to solve this without relying on the content of /etc/hosts?
我更改了上面的代码,以使其使用getaddrinfo,但我仍会取回回送设备的号码(127.0,0,1),而不是真实的IP地址:
I changed the above code so it makes use of getaddrinfo, but I still get back the loopback device's number (127.0,0,1) instead of the real IP address:
struct addrinfo hint = {0};
struct addrinfo *aip = NULL;
unsigned ip = 0;
struct sockaddr_in *sinp = NULL;
hint.ai_family = AF_INET; /* IPv4 */
hint.ai_socktype = SOCK_STREAM;
if(getaddrinfo(hostname, NULL, &hint, &aip) != 0) {
return 0;
}
sinp = (struct sockaddr_in *) aip->ai_addr;
ip = *(unsigned *) &sinp->sin_addr;
(我曾经用3个SOCK_STREAM,SOCK_DGRAM和SOCK_RAW取回3个addrinfo的列表,但提示阻止了这一点)
(I used to get back a list of 3 addrinfo's with the three SOCK_STREAM,SOCK_DGRAM and SOCK_RAW, but the hint prevents that)
所以我的问题仍然存在...
So my question still stands...
推荐答案
有POSIX函数getaddrinfo()
返回给定主机名的地址的链接列表,因此您只需要遍历该列表并找到非环回地址.
There is POSIX function getaddrinfo()
that returns linked list of addresses for given hostname, so you just need to go through that list and find non-loopback address.
请参见man getaddrinfo
.
这篇关于如何在C中获取我的非环回网络ip地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!