For communication between two hosts, I need to send the IP address of my host to another site. The problem is that if I ask for my IP address, maybe I will return my local loopback IP address (127.xxx) and not the network (ethernet) IP address.
I am using the following code:
char myhostname[32];
gethostname(myhostname, 32);
hp = gethostbyname(myhostname);
unsigned my_ip = *(unsigned*)(hp->h_addr);
if( (my_ip % 256) == 127) {
printf("Error, local IP address!");
return;
}
The only way to solve this is to make sure that my hostname in / etc / hosts is behind the real network address and not the local loopback (by default, for example, Ubuntu).
Is there a way to solve this without relying on the contents of / etc / hosts?
Edit: I changed the code above, so it uses getaddrinfo, but I still return the loopback device 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;
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 addrinfo SOCK_STREAM, SOCK_DGRAM SOCK_RAW, )
, ...