1 /* Host name canonicalization
3 Copyright (C) 2005 Free Software
6 Written by Derek Price <derek@ximbiot.com>.
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 "canon-host.h"
28 #include "getaddrinfo.h"
33 /* Store the last error for the single-threaded version of this function. */
34 static int last_cherror;
38 /* Single-threaded of wrapper for canon_host_r. After a NULL return, error
39 messages may be retrieved via ch_strerror().
42 canon_host (const char *host)
44 return canon_host_r (host, &last_cherror);
49 /* Returns a malloc'd string containing the canonical hostname associated with
50 HOST, or NULL if a canonical name cannot be determined. On NULL return, if
51 CHERROR is not NULL, *CHERROR will be set to an error code as returned by
52 getaddrinfo(). Error codes from CHERROR may be converted to a string
53 suitable for error messages by ch_strerror_r() or gai_strerror().
56 HOST must be a string representation of a resolvable name for this host.
57 Strings containing an IP address in dotted decimal notation will be
58 returned as-is, without further resolution.
60 The use of the word "canonical" in this context is unfortunate but
61 entrenched. The value returned by this function will be the end result
62 of the resolution of any CNAME chains in the DNS. There may only be one
63 such value for any given hostname, though the actual IP address
64 referenced by this value and the device using that IP address may each
65 actually have any number of such "canonical" hostnames. See the POSIX
66 getaddrinfo spec <http://www.opengroup.org/susv3xsh/getaddrinfo.html">,
67 RFC 1034 <http://www.faqs.org/rfcs/rfc1034.html>, & RFC 2181
68 <http://www.faqs.org/rfcs/rfc2181.html> for more on what this confusing
69 term really refers to.
72 canon_host_r (char const *host, int *cherror)
75 static struct addrinfo hints;
76 struct addrinfo *res = NULL;
79 hints.ai_flags = AI_CANONNAME;
80 status = getaddrinfo (host, NULL, &hints, &res);
83 retval = strdup (res->ai_canonname);
94 /* Return a string describing the last error encountered by canon_host. */
98 return gai_strerror (last_cherror);