I am writing a basic UDP Client-Server program and wasn’t getting the expected results from getbyhostname(). Here is a snippet from my code:
char *clientHostName = malloc(HOST_NAME_MAX);
gethostname(clientHostName, HOST_NAME_MAX);
printf("%s\n",clientHostName);
struct hostent thehost = gethostbyname(clientHostName);
printf("%ld\n",(*((unsigned long *) thehost->h_addr_list[0])));
So, the first print statement outputs what I expected, the name of my computer. However, I expect the second print statement to print out my IP Address. But no, it print out something like this: 4398250634. What is this that it is printing out? How do I get my IP Address?
First of all, you should not be using the
gethostbynameinterface. It’s deprecated and cannot deal with IPv6, which is a real-world, practical show-stopper in 2012. The proper interface to use isgetaddrinfo. Once you’ve usedgetaddrinfoto lookup a hostname and have it in a socket address form, you can usegetnameinfowith theNI_NUMERICHOSTflag to convert it to a printable IP-address form. This works for either IPv4 or IPv6, or for any future protocols.As for your particular printing issue, how do you expect
%ldto print an IP address? It prints a single number (long) in decimal (base 10). You could instead cast the pointer tounsigned char *and read 4 elements, each to be printed with%d, but again this is a bad approach.