C, Microsoft Windows

How to get the local IP address(es) using C in Windows

GetIpAddrTable function

You have to add the following libraries into your project:
ws2_32.lib and iphlpapi.lib.

Check this post on how to link your eclipse project with libraries.

#include <winsock2.h>
#include <iphlpapi.h>
#include <windows.h>
 
#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
 
int main(void)
{
	int i;
	PMIB_IPADDRTABLE pIPAddrTable;
	DWORD dwSize = 0;
	DWORD dwRetVal = 0;
	IN_ADDR IPAddr;
 
	pIPAddrTable = (MIB_IPADDRTABLE *) MALLOC(sizeof (MIB_IPADDRTABLE));
 
	if (pIPAddrTable) {
	  if (GetIpAddrTable(pIPAddrTable, &dwSize, 0) ==
	  ERROR_INSUFFICIENT_BUFFER) {
		FREE(pIPAddrTable);
		pIPAddrTable = (MIB_IPADDRTABLE *) MALLOC(dwSize);
	  }
	  if (pIPAddrTable == NULL) exit(1);
	}
 
	if ( (dwRetVal = GetIpAddrTable( pIPAddrTable, &dwSize, 0 )) != NO_ERROR ) exit(1);
 
	for (i=0; i < (int) pIPAddrTable->dwNumEntries; i++) {
	  IPAddr.S_un.S_addr = (u_long) pIPAddrTable->table[i].dwAddr;
	  printf("%s", inet_ntoa(IPAddr) );
	  IPAddr.S_un.S_addr = (u_long) pIPAddrTable->table[i].dwMask;
	  printf(" %s\n", inet_ntoa(IPAddr) );
	}
 
	if (pIPAddrTable) {
	  FREE(pIPAddrTable);
	  pIPAddrTable = NULL;
	}
}