Resolve hostname to ip address in C

Resolve hostname to ip address (TCP v4) in Windows using C and getaddrinfo.

#include <stdio.h>
#include <winsock2.h>
#include <ws2tcpip.h>
 
#pragma comment (lib, "Ws2_32.lib")
 
void resolve_hostname_to_ipaddress(char* hostname);
 
int main(int argc, char* argv[])
{
	resolve_hostname_to_ipaddress("hostname.com");
 
	return EXIT_SUCCESS;
}
 
void resolve_hostname_to_ipaddress(char* hostname)
{
	DWORD ppi = -1;
	struct addrinfo hints;
	struct addrinfo *ptr = NULL;
	struct addrinfo *result = NULL;
	struct sockaddr_in *sockaddr_ipv4 = NULL;
 
	WSADATA wsaData;
	int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (iResult != 0) {
		printf("WSAStartup failed: %dn", iResult);
	}
 
	ZeroMemory( &hints, sizeof(hints) );
	hints.ai_family = AF_UNSPEC;
 
	ppi = getaddrinfo(hostname, NULL, &hints, &result);
	if ( ppi != 0 ) {
		printf("getaddrinfo failed with error: %dn", ppi);
	}
	else {
		for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {
			switch (ptr->ai_family) {
			case AF_INET:
				sockaddr_ipv4 = (struct sockaddr_in *) ptr->ai_addr;
				printf("%sn", inet_ntoa(sockaddr_ipv4->sin_addr) );
				break;
			}
		}
		freeaddrinfo(result);
	}
	WSACleanup();
 
}
%d bloggers like this: