I am creating a winsocket app & want to know that if there's a method available to fetch the Dynamic IP of the local machine & not it's local address.
For eg: my local address may state 192.168.1.3 but my dynamic IP is depedent on my ISP location like 59.114.25.10

Using gethostbyname() & gethostname() returns the local IP address.
I need this so that my application can communicate over the internet & not just locally or the intranet.

You can use this (and probably add some error checking):

// Gets the local IP address
// IPv4 address and little-endian machine are assumed

#include <cstdio>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")

int main()
{
	WSADATA wsadata;
	WSAStartup( MAKEWORD(2, 2), &wsadata );

	char buffer[256];
	struct addrinfo * result;
	struct addrinfo hints = { 0 };
	hints.ai_family = AF_INET;

	gethostname( buffer, sizeof(buffer) ); // Get the standard host name for the local computer.
	getaddrinfo( buffer, NULL, &hints, &result );

	printf( "%s\n", buffer );
	struct addrinfo * ptr = result;
	while( ptr )
	{
		ULONG addr = ((struct sockaddr_in *)ptr->ai_addr)->sin_addr.S_un.S_addr;

		if (
			( ( addr              ) != 0x0100007F ) &&	// 127.0.0.1
			( ( addr & 0x000000FF ) != 0x0000000A ) &&	// 10.0.0.0/8 range
			( ( addr & 0x00000FFF ) != 0x000010AC ) &&	// 172.16.0.0/12 range
			( ( addr & 0x0000FFFF ) != 0x0000A8C0 )		// 192.168.0.0/16 range
			// ... other ranges you want to skip ...
			)
		{
			getnameinfo( ptr->ai_addr, ptr->ai_addrlen, buffer, sizeof(buffer), NULL, NULL, NI_NUMERICHOST );
			printf( "%s\n", buffer );
		}

		ptr = ptr->ai_next;
	}

	freeaddrinfo( result );
	WSACleanup();


	return 0;
}

You can achieve the same using gethostname() and the deprecated gethostbyname() by iterating through the h_addr_list list in the hostent * returned by gethostbyname().

@gashtio: This will only give me static IPs, but I need the dynamic IPs behind the routers.

Hmm, sorry, I thought that by dynamic you meant that you just get your address from a DHCP server and still connect directly to the internet, not behind a router.

Anyway, I don't think this can be done easily, your best shot is probably to connect to a HTTP server which reports your external IP, such as www.whatismyip.com, and parse the reply.

This article has been dead for over six months. Start a new discussion instead.