What happened to gethostbyname?

I am using this piece of code that I found at http://www.kutukupret.com/2009/09/28/gethostbyname-vs-getaddrinfo/ to do a dns search

#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 came across a strange 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?

+7
source share
2 answers

This is not an error, but rather a function of the inet_aton () function:

DESCRIPTION

The inet_aton () function converts the specified string to the Internet standard point-to-point, to the network address and stores the address in the presented structure.

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

abcd When four parts are specified, each is interpreted as a data byte and is assigned from left to right to four bytes of the Internet address.

ABC When a three-part address is specified, the last part is interpreted as a 16-bit value and placed in the far right 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 about it there , for example.

+17
source

POSIX.2004 says:

The argument name gethostbyname () must be the name node; the behavior of gethostbyname () when passing a numeric address bar is not specified. For IPv4, the numeric address string must be in decimal form with the decimal precision described in inet_addr ().

So, looking at it from the point of view of POSIX, you cannot expect anything by passing it an IP address.

On my system, the man page says the following:

If the name is an IPv4 or IPv6 address, the search is not performed, and gethostbyname () simply copies the name in the h_name field and its structural equivalent in_addr to the h_addr_list [0] field of the returned host structure.

It does not say anything about what happens if you give it an incomplete IP address so that everything can happen, including the behavior you observed.

For more information on how gethostbyname implemented on your system, you can check the documentation for the function and / or source code (if any).

+7
source

All Articles