tags:

views:

93

answers:

5

How can I get the IP address of the system.

I want the Ip address as I can see after doing ipconfig or /bin/ifconfig

+4  A: 

You mean 'IP Addresses' - use GetAdapterAddresses in Win32. There is sample code there.

It's a bit convoluted because you first call the API have to see how much memory you need, and then call the same API again with the required memory block. Then you have to walk the list of returned structures in that memory block as shown in the sample. What you are eventually gong to get to is this:

The SOCKET_ADDRESS structure is used in the IP_ADAPTER_ADDRESSES structure pointed to by the AdapterAddresses parameter. On the Microsoft Windows Software Development Kit (SDK) released for Windows Vista and later, the organization of header files has changed and the SOCKET_ADDRESS structure is defined in the Ws2def.h header file which is automatically included by the Winsock2.h header file. On the Platform SDK released for Windows Server 2003 and Windows XP, the SOCKET_ADDRESS structure is declared in the Winsock2.h header file. In order to use the IP_ADAPTER_ADDRESSES structure, the Winsock2.h header file must be included before the Iphlpapi.h header file.

At that point you can call WSAAddressToString to string-ize the IP address that's held inside the SOCKET_ADDRESS structure, whether it's IPv6 or IPv4.

Steve Townsend
You can pass in a reasonable value (e.g. 4KB) the first time, which will save you a second call in the common scneario.
MSalters
@MSalters - yes - another approach would be to try with some suitable multiple of `sizeof(struct)` - most machines will not have more than 10 network adapters, say.
Steve Townsend
@Steve Townsend: It depends. Where I work, having more 10 card adapters is quite common (well, on some servers at least).
ereOn
A: 

Your question isn't very specific, but this should help:

http://www.codeguru.com/forum/showthread.php?t=233261

Liggi
A: 

If you are behind a firewall and want to know your public IP address, you could use an HTTP client library to scrape web pages like this one (there was one that just returns the IP address as text/plain, but I can't find it right now).

Marcelo Cantos
In C++? (15 chars)
The Elite Gentleman
Thanks @The... Not reading tags properly is a bad habit of mine.
Marcelo Cantos
@Marcelo Cantos: [I know what you mean](http://stackoverflow.com/questions/3962395/really-simple-programming-languages/3963880#3963880 "not reading thouroghly") :)
Default
A: 

If you can access .NET Framework (managed C++) you can use System.Net.Dns.GetHostAddress method. See here for more: http://msdn.microsoft.com/en-us/library/system.net.dns.gethostaddresses.aspx You actually get an array of IPs since one domain name can correspond to more than one IP.

papadi
A: 

For local IP address, you can use winsock. Take a look at this example.

If you use winsock, make sure you add proper library in your project. For example, I've to add Ws2_32.lib in VS 2008.

Donotalo