CSCB09 2022 Summer Week 11 Lab

In this lab, you will learn and use getaddrinfo() for looking up the IPv4 addresses of a domain name aka host name. You will also learn freeaddrinfo() for freeing the data structure created by getaddrinfo().

getaddrinfo

getaddrinfo() takes many parameters because it can do many things; the man page can be overwhelming at first sight. On the bright side, it offers to completely fill in a sockaddr_in struct for you (or sockaddr_in6 when used for IPv6), ready for passing to connect().

You should read the man page, but here is an orientation:

int getaddrinfo(const char *host,
                const char *service,
                const struct addrinfo *hints,
                struct addrinfo **res);

For the purpose of hints, the following 4 fields in the addrinfo struct are of interest, and the other fields should be set to 0 (if number field) or NULL (if pointer field):

In the addrinfo struct you receive via res, the fields ai_family, ai_socktype, ai_protocol have actual resolved values (useful for calling socket()), plus:

Task

Your job is to complete getaddr.c to call getaddrinfo() and then use the provided print_inet4_addr() to print out all IPv4 addresses found.

After that, learn and use freeaddrinfo() to free the addrinfo linked list. I will use valgrind to check this!

Optional: If getaddrinfo() returns a non-zero number, learn and use gai_strerror() for the corresponding error message, print it to stderr, and exit.

Sample runs and outputs, assuming your executable is ./getaddr :

$ ./getaddr utsc.utoronto.ca
142.1.96.30
$ ./getaddr ageofempires.com | sort
20.112.250.133
20.231.239.246
20.236.44.162
20.53.203.50
20.76.201.171

The ageofempires.com example shows a case of multiple answers. Although the order can be different every time, piping to sort should yield a reproducible result, as shown.