1 /* Host name canonicalization
3 Copyright (C) 1995, 1999, 2000 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. */
25 #include <sys/types.h>
38 #ifdef HAVE_SYS_SOCKET_H
39 # include <sys/socket.h>
42 #ifdef HAVE_NETINET_IN_H
43 # include <netinet/in.h>
45 #ifdef HAVE_ARPA_INET_H
46 # include <arpa/inet.h>
53 /* Returns the canonical hostname associated with HOST (allocated in a static
54 buffer), or 0 if it can't be determined. */
56 canon_host (const char *host
)
58 #ifdef HAVE_GETHOSTBYNAME
59 struct hostent
*he
= gethostbyname (host
);
63 # ifdef HAVE_GETHOSTBYADDR
66 /* Try and get an ascii version of the numeric host address. */
67 switch (he
->h_addrtype
)
69 # ifdef HAVE_INET_NTOA
71 addr
= inet_ntoa (*(struct in_addr
*) he
->h_addr
);
73 # endif /* HAVE_INET_NTOA */
76 if (addr
&& strcmp (he
->h_name
, addr
) == 0)
78 /* gethostbyname has returned a string representation of the IP
79 address, for example, "127.0.0.1". So now, look up the host
80 name via the address. Although it may seem reasonable to look
81 up the host name via the address, we must not pass `he->h_addr'
82 directly to gethostbyaddr because on some systems he->h_addr
83 is located in a static library buffer that is reused in the
84 gethostbyaddr call. Make a copy and use that instead. */
85 char *h_addr_copy
= (char *) malloc (he
->h_length
);
86 if (h_addr_copy
== NULL
)
90 memcpy (h_addr_copy
, he
->h_addr
, he
->h_length
);
91 he
= gethostbyaddr (h_addr_copy
, he
->h_length
, he
->h_addrtype
);
95 # endif /* HAVE_GETHOSTBYADDR */
98 return (char *) (he
->h_name
);
100 #endif /* HAVE_GETHOSTBYNAME */
104 #ifdef TEST_CANON_HOST
106 main (int argc
, char **argv
)
109 for (i
= 1; i
< argc
; i
++)
111 char *s
= canon_host (argv
[i
]);
112 printf ("%s: %s\n", argv
[i
], (s
? s
: "<undef>"));
116 #endif /* TEST_CANON_HOST */