]>
diplodocus.org Git - nmh/blob - test/getcanon.c
2 * getcanon.c - Print the canonical name of a host, default to localhost.
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.
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 */
20 main(int argc
, char *argv
[])
22 char buf
[_POSIX_HOST_NAME_MAX
+ 1];
23 const char *hostname
= buf
;
24 struct addrinfo hints
, *res
;
27 /* Borrowed the important code below from LocalName() in sbr/mts.c. */
30 /* First get our local name. */
31 status
= gethostname(buf
, sizeof buf
);
32 } else if (argc
== 2) {
34 } else if (argc
> 2) {
35 fprintf(stderr
, "usage: %s [hostname]\n", argv
[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
;
45 if ((status
= getaddrinfo(hostname
, NULL
, &hints
, &res
)) == 0) {
46 printf("%s\n", res
->ai_canonname
);
49 printf("%s\n", hostname
);
52 fprintf(stderr
, "gethostname() failed: %s\n", strerror(errno
));