1 /* Host name canonicalization
3 Copyright (C) 1995, 1999, 2000, 2002, 2003, 2004, 2005 Free Software
6 Written by Miles Bader <miles@gnu.ai.mit.edu>
8 This program is free software; you can redistribute it and/or
9 modify it under the terms of the GNU General Public License as
10 published by the Free Software Foundation; either version 2, or (at
11 your option) any later version.
13 This program is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software Foundation,
20 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
26 #include <sys/types.h>
35 #ifdef HAVE_SYS_SOCKET_H
36 # include <sys/socket.h>
39 #ifdef HAVE_NETINET_IN_H
40 # include <netinet/in.h>
42 #ifdef HAVE_ARPA_INET_H
43 # include <arpa/inet.h>
48 /* Returns the canonical hostname associated with HOST (allocated in a static
49 buffer), or NULL if it can't be determined. */
51 canon_host (char const *host)
53 char *h_addr_copy = NULL;
57 struct addrinfo hint = { 0, };
58 struct addrinfo *res = NULL;
59 hint.ai_flags = AI_CANONNAME;
60 if (getaddrinfo (host, NULL, &hint, &res) == 0)
62 h_addr_copy = strdup (res->ai_canonname);
66 #elif HAVE_GETHOSTBYNAME
68 struct hostent *he = gethostbyname (host);
72 # ifdef HAVE_GETHOSTBYADDR
75 /* Try and get an ascii version of the numeric host address. */
76 switch (he->h_addrtype)
78 # ifdef HAVE_INET_NTOA
80 addr = inet_ntoa (*(struct in_addr *) he->h_addr);
82 # endif /* HAVE_INET_NTOA */
85 if (addr && strcmp (he->h_name, addr) == 0)
87 /* gethostbyname has returned a string representation of the IP
88 address, for example, "127.0.0.1". So now, look up the host
89 name via the address. Although it may seem reasonable to look
90 up the host name via the address, we must not pass `he->h_addr'
91 directly to gethostbyaddr because on some systems he->h_addr
92 is located in a static library buffer that is reused in the
93 gethostbyaddr call. Make a copy and use that instead. */
94 h_addr_copy = (char *) malloc (he->h_length);
95 if (h_addr_copy == NULL)
99 memcpy (h_addr_copy, he->h_addr, he->h_length);
100 he = gethostbyaddr (h_addr_copy, he->h_length, he->h_addrtype);
104 # endif /* HAVE_GETHOSTBYADDR */
107 h_addr_copy = strdup (he->h_name);
110 #endif /* HAVE_GETHOSTBYNAME */
115 #ifdef TEST_CANON_HOST
117 main (int argc, char **argv)
120 for (i = 1; i < argc; i++)
122 char *s = canon_host (argv[i]);
123 printf ("%s: %s\n", argv[i], (s ? s : "<undef>"));
127 #endif /* TEST_CANON_HOST */