]> diplodocus.org Git - nmh/blob - test/getcanon.c
context_foil.c: Move interface to own file.
[nmh] / test / getcanon.c
1 /* getcanon.c - Print the canonical name of a host, default to localhost.
2 *
3 * This code is Copyright (c) 2012, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
6 */
7
8 #include <netdb.h>
9 #include <sys/socket.h>
10 #include <sys/types.h>
11 #include <unistd.h>
12 #include <limits.h>
13 #include <string.h>
14 #include <stdio.h>
15 #include <errno.h>
16
17
18 int
19 main(int argc, char *argv[])
20 {
21 char buf[_POSIX_HOST_NAME_MAX + 1];
22 const char *hostname;
23 struct addrinfo hints, *res;
24
25 /* Borrowed the important code below from LocalName() in sbr/mts.c. */
26
27 if (argc > 2) {
28 fprintf(stderr, "usage: %s [hostname]\n", argv[0]);
29 return 1;
30 }
31 if (argc == 2)
32 hostname = argv[1];
33 else {
34 /* First get our local name. */
35 if (gethostname(buf, sizeof buf)) {
36 fprintf(stderr, "gethostname() failed: %s\n", strerror(errno));
37 return 1;
38 }
39 hostname = buf;
40 }
41
42 /* Now fully qualify the hostname. */
43 memset(&hints, 0, sizeof hints);
44 hints.ai_flags = AI_CANONNAME;
45 hints.ai_family = AF_UNSPEC;
46
47 if (getaddrinfo(hostname, NULL, &hints, &res)) {
48 puts(hostname);
49 return 1;
50 }
51 puts(res->ai_canonname);
52
53 return 0;
54 }