summaryrefslogtreecommitdiff
path: root/pgm4/inet_addrs.d/gethost.c
blob: dcfc7fddcbf60fc14e4fc65df3c43c9425ef9e12 (plain) (blame)
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
55
56
57
// Using getnameinfo() to get host name for a
// given IP address (argv[1]).
//
// P. Kearns, February 2009

#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
  
  int ecode;
  struct in_addr fillin;
  struct sockaddr_in addr;
  char host[NI_MAXHOST];

  if (argc != 2) {
    fprintf(stderr,"usage: gethost address\n");
    exit(1);
  }	

// Dotted decimal to binary IP address.

  ecode = inet_pton(AF_INET, argv[1], &fillin);
  if (ecode == 0) {
        fprintf(stderr,"inet_pton: invalid address\n");
        exit(1);
  }
  if (ecode < 0) {
	perror("inet_pton"); exit(1);
        exit(1);
  }

// Fill in blanks of a sockaddr_in after zeroing it out.

  memset(&addr, 0, sizeof(addr));
  addr.sin_family = AF_INET;
  addr.sin_port = htons(0);
  memcpy(&(addr.sin_addr), &fillin, sizeof(addr.sin_addr));

// Do the lookup.

  ecode = getnameinfo((struct sockaddr *) &addr, sizeof(addr),
                          host, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
  if (ecode) {
    fprintf(stderr, "getnameinfo: %s\n", gai_strerror(ecode));
    exit(1);
  }

  printf("Hostname: %s\n", host); 
  exit(0);
}