File: getcanon.c

package info (click to toggle)
nmh 1.8-4
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 7,860 kB
  • sloc: ansic: 50,445; sh: 22,697; makefile: 1,138; lex: 740; perl: 509; yacc: 265
file content (54 lines) | stat: -rw-r--r-- 1,232 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/* getcanon.c - Print the canonical name of a host, default to localhost.
 *
 * This code is Copyright (c) 2012, by the authors of nmh.  See the
 * COPYRIGHT file in the root directory of the nmh distribution for
 * complete copyright information.
 */

#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <limits.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>


int
main(int argc, char *argv[])
{
  char buf[_POSIX_HOST_NAME_MAX + 1];
  const char *hostname;
  struct addrinfo hints, *res;

  /* Borrowed the important code below from LocalName() in sbr/mts.c. */

  if (argc > 2) {
    fprintf(stderr, "usage: %s [hostname]\n", argv[0]);
    return 1;
  }
  if (argc == 2)
    hostname = argv[1];
  else {
    /* First get our local name. */
    if (gethostname(buf, sizeof buf)) {
        fprintf(stderr, "gethostname() failed: %s\n", strerror(errno));
        return 1;
    }
    hostname = buf;
  }

  /* Now fully qualify the hostname. */
  memset(&hints, 0, sizeof hints);
  hints.ai_flags = AI_CANONNAME;
  hints.ai_family = AF_UNSPEC;

  if (getaddrinfo(hostname, NULL, &hints, &res)) {
    puts(hostname);
    return 1;
  }
  puts(res->ai_canonname);

  return 0;
}