]>
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];
24 struct addrinfo hints
, *res
;
26 /* Borrowed the important code below from LocalName() in sbr/mts.c. */
29 fprintf(stderr
, "usage: %s [hostname]\n", argv
[0]);
35 /* First get our local name. */
36 if (gethostname(buf
, sizeof buf
)) {
37 fprintf(stderr
, "gethostname() failed: %s\n", strerror(errno
));
43 /* Now fully qualify the hostname. */
44 memset(&hints
, 0, sizeof hints
);
45 hints
.ai_flags
= AI_CANONNAME
;
46 hints
.ai_family
= AF_UNSPEC
;
48 if (getaddrinfo(hostname
, NULL
, &hints
, &res
)) {
52 puts(res
->ai_canonname
);