Exemple gethostbyname

2007-04-09

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/param.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h> /* strcpy() */
#include <stdlib.h> /* exit() */

int main()
{
        char hostbuf[MAXHOSTNAMELEN];
        struct hostent *hp;

        /* Get the local hostname */
        if (gethostname(hostbuf, sizeof(hostbuf)) < 0)
                        strcpy(hostbuf, "localhost");
        printf("hostname = \"%s\"\n", hostbuf);

        /* canonicalize it and get aliases */
        if ((hp = gethostbyname(hostbuf)) == NULL)
                perror("gethostbyname"), exit(2);
        printf("canonical = \"%s\"\n", hp->h_name);
        while(*hp->h_aliases != NULL) {
                printf("alias: \"%s\"\n", *hp->h_aliases);
                ++hp->h_aliases;
        }

        return 0;
}