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