Some Simple Examples

We will now look at a few examples of code written from scratch and old code that has been updated to deal with IPv6. The examples are written for Unix-like systems, but the situation on Windows should be very similar apart from the use of Winsock2.h and Ws2tcpip.h rather than the Unix socket headers. You need to make sure you use a recent version of the Windows Platform SDK to get headers and libraries that include IPv6 support. The SDK is available from http://msdn.microsoft.com/.

Parsing and Printing Names and Addresses

In this example, we look at how you might use getaddrinfo and getnameinfo. The program in Example 8-1 reads a list of hostnames, one per line. For each name it calls getaddrinfo with the PF_UNSPEC flag to get a list of the addresses associated with that name. Then for each of the addresses we call getnameinfo with the NI_NUMERICHOST flag to convert that address into the numeric form, rather than resolving the address by DNS or some other method.

Example 8-1. C resolver code

#include <sys/types.h> #include <sys/socket.h> #include <ctype.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char **argv) { int error; char *p, name[NI_MAXHOST], addr[NI_MAXHOST]; struct addrinfo hints, *res, *r; while (fgets(name, sizeof(name), stdin) != NULL) { /* Cut the string at first whitespace */ for (p = name; *p; p++) if (isspace(*p)) { *p = '\0'; break; } printf("%s\t", name); /* Try to look up the ...

Get IPv6 Network Administration now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.