Groppe
Groppe

Reputation: 3879

How does getbyhostname() work?

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?

Upvotes: 0

Views: 1914

Answers (2)

paxdiablo
paxdiablo

Reputation: 882386

The functions you're calling, and the field you're examining, give you a 32-bit variable with each 8-bit octet containing on segment of your IP address. The following code:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>

#define HOST_NAME_MAX 1024

int main (void) {
    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])));
    printf("%08lx\n",(*((unsigned long *) thehost->h_addr_list[0])));
    return 0;
}

on my Xubuntu box gives:

formaldehyde
16842879
0101007f

and, if you break down that hex number at the end into 01, 01, 00 and 7f, that's (in reverse order due to my CPU) 127.0.1.1, one of the loopback addresses.

Upvotes: 3

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215517

First of all, you should not be using the gethostbyname interface. It's deprecated and cannot deal with IPv6, which is a real-world, practical show-stopper in 2012. The proper interface to use is getaddrinfo. Once you've used getaddrinfo to lookup a hostname and have it in a socket address form, you can use getnameinfo with the NI_NUMERICHOST flag 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 %ld to print an IP address? It prints a single number (long) in decimal (base 10). You could instead cast the pointer to unsigned char * and read 4 elements, each to be printed with %d, but again this is a bad approach.

Upvotes: 7

Related Questions