]> diplodocus.org Git - nmh/blob - test/getcanon.c
mhlsbr.c: Don't strchr(3) non-string NUL-less buffer.
[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;
24 struct addrinfo hints, *res;
25
26 /* Borrowed the important code below from LocalName() in sbr/mts.c. */
27
28 if (argc > 2) {
29 fprintf(stderr, "usage: %s [hostname]\n", argv[0]);
30 return 1;
31 }
32 if (argc == 2)
33 hostname = argv[1];
34 else {
35 /* First get our local name. */
36 if (gethostname(buf, sizeof buf)) {
37 fprintf(stderr, "gethostname() failed: %s\n", strerror(errno));
38 return 1;
39 }
40 hostname = buf;
41 }
42
43 /* Now fully qualify the hostname. */
44 memset(&hints, 0, sizeof hints);
45 hints.ai_flags = AI_CANONNAME;
46 hints.ai_family = AF_UNSPEC;
47
48 if (getaddrinfo(hostname, NULL, &hints, &res)) {
49 puts(hostname);
50 return 1;
51 }
52 puts(res->ai_canonname);
53
54 return 0;
55 }