Resolve Hostname to IP Address

AceInfinity

Emeritus, Contributor
Joined
Feb 21, 2012
Posts
1,728
Location
Canada
Here's a short example on some code I wrote to resolve a hostname to an IP address. The gethostbyname() function has been depreciated, yet many people still use it. The getaddrinfo() function is the proper way, and so I thought some people might learn from the example:

Code:
[NO-PARSE]/*
* Author: AceInfinity
* Date:   2015-02-01 11:48:22
* File:   main.c
* Last Modified time: 2015-02-02 21:23:07
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define _WIN32_WINNT 0x0501
#include <winsock2.h>
#include <ws2tcpip.h>

int ws_init()
{
  static WSADATA wsa_data;
  return WSAStartup(WINSOCK_VERSION, &wsa_data);
}

int ws_destroy() { return WSACleanup(); }

int resolve_ip_addr(const char *hostname, const char *service, char *ip_result, size_t len)
{
  int ret;
  struct addrinfo hints;
  memset(&hints, 0, sizeof(hints));
  struct addrinfo result, *p_result = &result;
  if ((ret = getaddrinfo(hostname, service, &hints, &p_result)) != 0) return ret;
  // while (p_result->ai_next != NULL) { p_result = p_result->ai_next; }
  char *ip = inet_ntoa(((struct sockaddr_in *)p_result->ai_addr)->sin_addr);
  if (ip == NULL) return -1;
  strncpy(ip_result, ip, len - 1);
  ip_result[len - 1] = 0;
  return 0;
}

int main(void)
{
  if (ws_init() != 0)
  {
    puts("winsock initialization failed.");
    exit(1);
  }

  char ip[16];
  if (resolve_ip_addr("google.ca", "http", ip, 16) < 0)
  {
    puts("failed to resolve ip address from hostname.");
    exit(1);
  }
  puts(ip);

  if (ws_destroy() != 0)
  {
    puts("winsock cleanup failed.");
    exit(1);
  }
  exit(0);
}[/NO-PARSE]
 

Has Sysnative Forums helped you? Please consider donating to help us support the site!

Back
Top