Get IP address of network adapter in C – Unicode

You will need to include the libraries ws2_32.lib and iphlpapi.lib into your project.

GetAdaptersAddresses – retrieves the addresses associated with the adapters on the local computer.

WSAAddressToStringW – converts all components of a sockaddr structure into a human-readable string representation of the address. This is intended to be used mainly for display purposes. (Unicode names)

#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <iphlpapi.h>
 
#define WORKING_BUFFER_SIZE 	15000
#define MAX_TRIES 		3
 
void ListLocalIPs(void) {
  DWORD outBufLen = WORKING_BUFFER_SIZE;
  DWORD dwRetVal;
  PIP_ADAPTER_ADDRESSES pAddresses = NULL;
  PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL;
  ULONG Iterations = 0;
  DWORD retval=0;
  WSADATA wsaData;
  DWORD length = 16;
  WCHAR buf[length];
 
  pAddresses = (IP_ADAPTER_ADDRESSES *) malloc(outBufLen);
  memset(pAddresses, 0, outBufLen);
 
  if (pAddresses == NULL) return;
  do {
      dwRetVal = GetAdaptersAddresses(AF_INET, GAA_FLAG_INCLUDE_PREFIX, NULL, pAddresses, &outBufLen);
      if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
          if (pAddresses) {
		free(pAddresses);
		pAddresses = NULL;
	  }
      } else break;
 
      Iterations++;
  } while((dwRetVal == ERROR_BUFFER_OVERFLOW) && (Iterations < MAX_TRIES));
 
  retval = WSAStartup(MAKEWORD(2, 2), &wsaData);
  if (retval != 0){
      if (pAddresses) {
	  free(pAddresses);
	  pAddresses = NULL;
      }
 
      return;
  }
 
  if (dwRetVal == NO_ERROR){
	  printf("Network Adapters IP addresses\n");
	  printf("*****************************\n");
	  pCurrAddresses = pAddresses;
 
	  while (pCurrAddresses) {
	      memset(buf, 0, length);
 
	      if (pCurrAddresses->FirstUnicastAddress != NULL)
	          if(WSAAddressToStringW(pCurrAddresses->FirstUnicastAddress->Address.lpSockaddr,
			pCurrAddresses->FirstUnicastAddress->Address.iSockaddrLength,
			   NULL, buf, &length) != 0) continue;
 
	      wprintf(L"Adapter %s, IP address: %s\n", pCurrAddresses->FriendlyName, buf);
	      pCurrAddresses = pCurrAddresses->Next;
	  }
  }
 
  if (pAddresses) {
      free(pAddresses);
      pAddresses = NULL;
  }
 
  WSACleanup();
}
 
int main(void) {
    ListLocalIPs();
    return EXIT_SUCCESS;
}
Categories: C Tags: , , ,
%d bloggers like this: