aboutsummaryrefslogtreecommitdiff
path: root/pa6_threaded_resolver/util.c
blob: 04e9cb34622d500e48ddead9452e0d5193490278 (plain)
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
 * File: util.c
 * Author: Andy Sayler
 * Modified: Shiv Mishra
 * Project: CSCI 3753 Programming Assignment 5
 * Create Date: 2012/02/01
 * Modify Date: 2012/02/01
 * Modify Date: 2016/09/26
 * Description:
 * 	This file contains declarations of utility functions for
 *      Programming Assignment 5.
 *
 */

#include "util.h"

int dnslookup(const char *hostname, char *firstIPstr, int maxSize) {

  /* Local vars */
  struct addrinfo *headresult = NULL;
  struct addrinfo *result = NULL;
  struct sockaddr_in *ipv4sock = NULL;
  struct in_addr *ipv4addr = NULL;
  char ipv4str[INET_ADDRSTRLEN];
  char ipstr[INET6_ADDRSTRLEN];
  int addrError = 0;

  /* DEBUG: Print Hostname*/
#ifdef UTIL_DEBUG
  fprintf(stderr, "%s\n", hostname);
#endif

  /* Lookup Hostname */
  addrError = getaddrinfo(hostname, NULL, NULL, &headresult);
  if (addrError) {
    fprintf(stderr, "Error looking up Address: %s\n", gai_strerror(addrError));
    return UTIL_FAILURE;
  }
  /* Loop Through result Linked List */
  for (result = headresult; result != NULL; result = result->ai_next) {
    /* Extract IP Address and Convert to String */
    if (result->ai_addr->sa_family == AF_INET) {
      /* IPv4 Address Handling */
      ipv4sock = (struct sockaddr_in *)(result->ai_addr);
      ipv4addr = &(ipv4sock->sin_addr);
      if (!inet_ntop(result->ai_family, ipv4addr, ipv4str, sizeof(ipv4str))) {
        perror("Error Converting IP to String");
        return UTIL_FAILURE;
      }
#ifdef UTIL_DEBUG
      fprintf(stdout, "%s\n", ipv4str);
#endif
      strncpy(ipstr, ipv4str, sizeof(ipstr));
      ipstr[sizeof(ipstr) - 1] = '\0';
    } else if (result->ai_addr->sa_family == AF_INET6) {
      /* IPv6 Handling */
#ifdef UTIL_DEBUG
      fprintf(stdout, "IPv6 Address: Not Handled\n");
#endif
      strncpy(ipstr, "UNHANDELED", sizeof(ipstr));
      ipstr[sizeof(ipstr) - 1] = '\0';
    } else {
      /* Unhandlded Protocol Handling */
#ifdef UTIL_DEBUG
      fprintf(stdout, "Unknown Protocol: Not Handled\n");
#endif
      strncpy(ipstr, "UNHANDELED", sizeof(ipstr));
      ipstr[sizeof(ipstr) - 1] = '\0';
    }
    /* Save First IP Address */
    if (result == headresult) {
      strncpy(firstIPstr, ipstr, maxSize);
      firstIPstr[maxSize - 1] = '\0';
    }
  }

  /* Cleanup */
  freeaddrinfo(headresult);

  return UTIL_SUCCESS;
}