Hi everybody,
I am not sure if this question belongs in the Linux or in the Network forum, but I think it is a mire Linux related question:
I am trying to determine the IP address of the local computer, so that I can compare it with the IP address a server tells me, my computer has. That way I can find out if I am behind a NAT or not.
I tried the following code:
char szHostName[128];
char ip[16] = "\0";
struct hostent *pHost;
int i;
if(gethostname(szHostName, 128) == 0)
{
pHost = gethostbyname(szHostName);
for(i=0; i<pHost->h_length; i++)
{
if(i > 0)
sprintf(ip, "%s.", ip);
sprintf(ip, "%s%u", ip, (unsigned int)((unsigned char *)pHost->h_addr_list[0]));
}
cout << "Address : " << ip << endl;
}
return 0;
The output is
Address : 127.0.0.1
I also tried this:
char ac[80];
gethostname(ac, sizeof(ac));
cout << "Host name is " << ac << "." << endl;
struct hostent *phe = gethostbyname(ac);
if (phe == 0) {
cerr << "Yow! Bad host lookup." << endl;
return 1;
}
for (int i = 0; phe->h_addr_list != 0; ++i) {
struct in_addr addr;
memcpy(&addr, phe->h_addr_list, sizeof(struct in_addr));
cout << "Address " << i << ": " << inet_ntoa(addr) << endl;
}
And get:
Host name is Sam.
Address 0: 127.0.0.1
But the IP address of eth0 is 10.10.152.49! How could my programm find out this address???
Thanks!
Nathan