What's wrong with gethostbyname?

Ottavio Campana picture Ottavio Campana · Jul 13, 2011 · Viewed 26.2k times · Source

I am using this snippet of code I found in http://www.kutukupret.com/2009/09/28/gethostbyname-vs-getaddrinfo/ to perform dns lookups

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char *argv[ ]) {
    struct hostent *h;

    /* error check the command line */
    if(argc != 2) {
        fprintf(stderr, "Usage: %s hostname\n", argv[0]);
        exit(1);
    }

    /* get the host info */
    if((h=gethostbyname(argv[1])) == NULL) {
        herror("gethostbyname(): ");
        exit(1);
    }
    else     
        printf("Hostname: %s\n", h->h_name);

    printf("IP Address: %s\n", inet_ntoa(*((struct in_addr *)h->h_addr)));     
    return 0;
}

I am facing a weird fact

./test www.google.com
Hostname: www.l.google.com
IP Address: 209.85.148.103

works fine, but if I try to resolve an incomplete IP address I get this

./test 10.1.1
Hostname: 10.1.1
IP Address: 10.1.0.1

I would expect an error like the following

./test www.google
gethostbyname(): : Unknown host

but the program seems to work.

Any idea why?

Answer

Igor Korkhov picture Igor Korkhov · Jul 13, 2011

It is not a bug but rather a feature of inet_aton() function:

DESCRIPTION

The inet_aton() function converts the specified string, in the Internet standard dot notation, to a network address, and stores the address in the structure provided.

Values specified using dot notation take one of the following forms:

a.b.c.d When four parts are specified, each is interpreted as a byte of data and assigned, from left to right, to the four bytes of an internet address.

a.b.c When a three-part address is specified, the last part is interpreted as a 16-bit quantity and placed in the rightmost two bytes of the network address. This makes the three-part address format convenient for specifying Class B network addresses as 128.net.host.

You can read more about this there, for example.