The getaddrinfo function is used to resolve both IPv4 and IPv6 hostnames. This document shows an easy example of how to use getaddrinfo on Windows VC++ platform.

Before you start writing

First of all, you would need a winsock2 environment. If it is too old, it will not include getaddrinfo and struct addrinfo. Because you will be using winsock2, you would have to link to ws2_32.lib.

I would suggest using newer versions than WindowsXP. The previous versions does not include IPv6 environment.

The default setting of WindowsXP disables IPv6 environment. Therefore, you would have to enable IPv6 by using the command "ipv6 install". You do not need to do this multiple times. The configuration will be held even after the host is rebooted.

You can use getaddrinfo even if you did not do "ipv6 install". However, getaddrinfo will only resolve IPv4 address.

Simple sample code

The following example shows you how to resolve an IPv4 address.

#include <winsock2.h>
#include <ws2tcpip.h>

 char *hostname = "localhost";
 struct addrinfo hints, *res;
 struct in_addr addr;
 int err;

 WSAData data;
 WSAStartup(MAKEWORD(2,0), &data);

 memset(&hints, 0, sizeof(hints));
 hints.ai_socktype = SOCK_STREAM;
 hints.ai_family = AF_INET;

 if ((err = getaddrinfo(hostname, NULL, &hints, &res)) != 0) {
   printf("error %d\n", err);
   return 1;

 addr.S_un = ((struct sockaddr_in *)(res->ai_addr))->sin_addr.S_un;

 printf("ip address : %s\n", inet_ntoa(addr));



 return 0;

Please note that you would need to use freeaddrinfo to free the memory allocated by getaddrinfo. It is likely to forget using freeaddrinfo, and cause a memory leak.


Copyright (C) GeekPage.JP. All rights reserved.