*** empty log message ***
[coreutils.git] / lib / canon-host.c
blob0c7eac4f0685614c001bd313d5b2182472392b69
1 /* Host name canonicalization
3 Copyright (C) 1995, 1999 Free Software Foundation, Inc.
5 Written by Miles Bader <miles@gnu.ai.mit.edu>
7 This program is free software; you can redistribute it and/or
8 modify it under the terms of the GNU General Public License as
9 published by the Free Software Foundation; either version 2, or (at
10 your option) any later version.
12 This program is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software Foundation,
19 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
21 #ifdef HAVE_CONFIG_H
22 # include <config.h>
23 #endif
25 #include <sys/types.h>
26 #ifdef HAVE_UNISTD_H
27 # include <unistd.h>
28 #endif
29 #ifdef HAVE_STRING_H
30 # include <string.h>
31 #endif
32 #ifdef HAVE_NETDB_H
33 # include <netdb.h>
34 #endif
35 #ifdef HAVE_SYS_SOCKET_H
36 # include <sys/socket.h>
37 #endif
39 #ifdef HAVE_NETINET_IN_H
40 # include <netinet/in.h>
41 #endif
42 #ifdef HAVE_ARPA_INET_H
43 # include <arpa/inet.h>
44 #endif
46 void free ();
48 /* Returns the canonical hostname associated with HOST (allocated in a static
49 buffer), or 0 if it can't be determined. */
50 char *
51 canon_host (const char *host)
53 #ifdef HAVE_GETHOSTBYNAME
54 struct hostent *he = gethostbyname (host);
56 if (he)
58 # ifdef HAVE_GETHOSTBYADDR
59 char *addr = 0;
61 /* Try and get an ascii version of the numeric host address. */
62 switch (he->h_addrtype)
64 # ifdef HAVE_INET_NTOA
65 case AF_INET:
66 addr = inet_ntoa (*(struct in_addr *) he->h_addr);
67 break;
68 # endif /* HAVE_INET_NTOA */
71 if (addr && strcmp (he->h_name, addr) == 0)
73 /* gethostbyname has returned a string representation of the IP
74 address, for example, "127.0.0.1". So now, look up the host
75 name via the address. Although it may seem reasonable to look
76 up the host name via the address, we must not pass `he->h_addr'
77 directly to gethostbyaddr because on some systems he->h_addr
78 is located in a static library buffer that is reused in the
79 gethostbyaddr call. Make a copy and use that instead. */
80 char *h_addr_copy = strdup (he->h_addr);
81 if (h_addr_copy == NULL)
82 he = NULL;
83 else
85 he = gethostbyaddr (h_addr_copy, he->h_length, he->h_addrtype);
86 free (h_addr_copy);
89 # endif /* HAVE_GETHOSTBYADDR */
91 if (he)
92 return (char *) (he->h_name);
94 #endif /* HAVE_GETHOSTBYNAME */
95 return 0;
98 #ifdef TEST_CANON_HOST
99 int
100 main (int argc, char **argv)
102 int i;
103 for (i = 1; i < argc; i++)
105 char *s = canon_host (argv[i]);
106 printf ("%s: %s\n", argv[i], (s ? s : "<undef>"));
108 exit (0);
110 #endif /* TEST_CANON_HOST */