.
[gnulib.git] / lib / canon-host.c
1 /* Host name canonicalization
2
3    Copyright (C) 1995 Free Software Foundation, Inc.
4
5    Written by Miles Bader <miles@gnu.ai.mit.edu>
6
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.
11
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.
16
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
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
20
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
24
25 #ifdef HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28 #ifdef HAVE_STRING_H
29 #include <string.h>
30 #endif
31 #ifdef HAVE_NETDB_H
32 #include <netdb.h>
33 #endif
34
35 #ifdef HAVE_NETINET_IN_H
36 #include <netinet/in.h>
37 #endif
38 #ifdef HAVE_ARPA_INET_H
39 #include <arpa/inet.h>
40 #endif
41
42 /* Returns the canonical hostname associated with HOST (allocated in a static
43    buffer), or 0 if it can't be determined.  */
44 char *
45 canon_host (host)
46      char *host;
47 {
48 #ifdef HAVE_GETHOSTBYNAME
49   struct hostent *he = gethostbyname (host);
50
51   if (he)
52     {
53 #ifdef HAVE_GETHOSTBYADDR
54       char *addr = 0;
55
56       /* Try and get an ascii version of the numeric host address.  */
57       switch (he->h_addrtype)
58         {
59 #ifdef HAVE_INET_NTOA
60         case AF_INET:
61           addr = inet_ntoa (*(struct in_addr *)he->h_addr);
62           break;
63 #endif /* HAVE_INET_NTOA */
64         }
65
66       if (addr && strcmp (he->h_name, addr) == 0)
67         /* gethostbyname() cheated!  Lookup the host name via the address
68            this time to get the actual host name.  */
69         he = gethostbyaddr (he->h_addr, he->h_length, he->h_addrtype);
70 #endif HAVE_GETHOSTBYADDR
71
72       if (he)
73         return he->h_name;
74     }
75
76 #else /* ! HAVE_GETHOSTBYNAME */
77   return 0;
78 #endif /* HAVE_GETHOSTBYNAME */
79 }