test_gethostbyname.c revision e16cb84e2324f05334d18dcf5956f20f44262b62
1#include <unistd.h>
2#include <errno.h>
3#include <string.h>
4#include <stdio.h>
5#include <sys/types.h>
6#include <netdb.h>
7
8int  main( int  argc, char**  argv )
9{
10    char*            hostname = "localhost";
11    struct hostent*  hent;
12    int    i, ret;
13
14    if (argc > 1)
15        hostname = argv[1];
16
17    hent = gethostbyname(hostname);
18    if (hent == NULL) {
19        printf("gethostbyname(%s) returned NULL !!\n", hostname);
20        return 1;
21    }
22    printf( "gethostbyname(%s) returned:\n", hostname);
23    printf( "  name: %s\n", hent->h_name );
24    printf( "  aliases:" );
25    for (i = 0; hent->h_aliases[i] != NULL; i++)
26        printf( " %s", hent->h_aliases[i] );
27    printf( "\n" );
28    printf( "  address type: " );
29    switch (hent->h_addrtype) {
30        case AF_INET:  printf( "AF_INET\n"); break;
31        case AF_INET6: printf( "AF_INET6\n"); break;
32        default: printf("UNKNOWN (%d)\n", hent->h_addrtype);
33    }
34    printf( "  address: " );
35    switch (hent->h_addrtype) {
36        case AF_INET:
37            {
38                const char*  dot = "";
39                for (i = 0; i < hent->h_length; i++) {
40                    printf("%s%d", dot, ((unsigned char*)hent->h_addr)[i]);
41                    dot = ".";
42                }
43            }
44            break;
45
46        default:
47            for (i = 0; i < hent->h_length; i++) {
48                printf( "%02x", ((unsigned char*)hent->h_addr)[i] );
49            }
50    }
51    printf("\n");
52    return 0;
53}
54