3 * Canonicalize a hostname
5 * Copyright (C) 1987-1998 by the Massachusetts Institute of Technology
6 * For copying and distribution information, please see the file
10 #include <mit-copyright.h>
13 #include <sys/types.h>
16 #include <sys/utsname.h>
20 #include <sys/socket.h>
22 #include <netinet/in.h>
32 static struct hostent *local_gethostbyname(void)
37 return gethostbyname(name.nodename);
40 gethostname(hostname, sizeof(hostname));
41 hostname[sizeof(hostname)-1] = 0;
42 return gethostbyname(hostname);
46 static char *local_domain(void)
48 static char *domain = NULL;
56 if (mr_host(hostbuf, sizeof(hostbuf)) == MR_SUCCESS)
58 cp = strchr(hostbuf, '.');
60 domain = strdup(++cp);
64 hp = local_gethostbyname();
67 cp = strchr(hp->h_name, '.');
69 domain = strdup(++cp);
80 * Canonicalize hostname:
81 * if it is in double-quotes, then strip the quotes and return the name.
82 * if it is in the namespace, call the nameserver to expand it
83 * otherwise uppercase it and append the default domain (using an, er,
84 * undocumented global of the nameserver).
86 * Assumes that host was allocated using malloc(); it may be freed or
87 * realloc'ed, so the old pointer should not be considered valid.
90 char *canonicalize_hostname(char *host)
97 if (len > 2 && host[0] == '"' && host[len - 1] == '"')
99 tbuf = malloc(len - 1);
102 strncpy(tbuf, host + 1, len - 2);
103 tbuf[len - 2] = '\0';
108 if (strchr(host, '*') || strchr(host, '?') || *host == '[')
111 hp = gethostbyname(host);
115 host = realloc(host, strlen(hp->h_name) + 1);
117 strcpy(host, hp->h_name);
122 /* can't get name from nameserver; fix up the format a bit */
123 cp = strchr(host, '.');
126 tbuf = malloc(strlen(host) + strlen(local_domain()) + 2);
129 sprintf(tbuf, "%s.%s", host, local_domain());
133 else if (strcasecmp(cp + 1, local_domain()) != 0)
136 /* This is a host in our local domain, so capitalize it. */
137 for (cp = host; *cp; cp++)