Resolve hostname to ip address in C

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

#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)
{
    struct hostent *he;
    struct in_addr **addr_list;
    int i;
 
	WSADATA wsaData;
	int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (iResult != 0) {
		printf("WSAStartup failed: %dn", iResult);
	}
 
	if ( (he = gethostbyname( hostname ) ) == NULL)
    {
        printf("gethostbyname failedn");
    }
 
    addr_list = (struct in_addr **) he->h_addr_list;
 
    for(i = 0; addr_list[i] != NULL; i++)
    {
		printf("%sn", inet_ntoa(*addr_list[i]) );
    }
 
    WSACleanup();
}
%d bloggers like this: