is there a way to get the IP number from gethostname()?
We are randomly generating IP addresses for the computers in the lab we are in. We use gethostbyname(<random ip>) to get the IP of a computer.
What we want to do essentially is compare the ip that we get from gethostbyname() with what we get from gethostname().
We tried:
struct hostent* host;
char temp[MAX_LEN];
gethostname(temp, MAX_LEN);
host = gethostbyname(<random ip address>)
if(host->h_name == temp) printf("They are the same\n");
The problem is, is that host->h_name is ‘172.125.45.1’ (i made that
up) and temp is ‘u-my_comp’
so we cant compare the strings cause one gives us the name of the computer (u-my_comp), and the other gives the ip…
Is there anyway to make these functions return the same type of value?
we have tried doing something like
gethostname(temp, 24)
temp_host = gethostbyname(temp)
in hopes that now we could compare temp_host->h_name with host->h_name…but yeah, that didnt work either.
Any ideas?
thanks!
gethostbyname()is for converting a hostname into a socket address. If the “hostname” you supply is a dotted-quad IPv4 address, that will be all you get in theh_nameparameter of the result.To convert a socket address back into a name what you want is the companion function
gethostbyaddr()– except that you don’t, because bothgethostbyname()andgethostbyaddr()are deprecated. Instead, you should be usinggetaddrinfo()andgetnameinfo().For example: