How would I go about finding the external IP of a user in C++? I need a method that would work for any system, not just mine. Additionally, the system could be behind a router, thus NAT would come into play making it harder to retrieve the external IP.
Ideally, I'd like to do this without using any 3rd party service like whatsmyip. However, I'm not sure if this is possible. If I don't use a 3rd party service, I'd have to go through the router and if ping is disabled I'm guessing this might not be possible (I could be wrong, not too sure).
If I were to use a 3rd party service like whatsmyip, how might I go about this? Is there a web service that they expose? I've seen this link: http://automation.whatismyip.com/n09230945.asp but it doesn't seem to be working. Would it be possible to fetch the external IP by using some HTTP methods and retrieve it, or would I effectively need to scrape the page to get the IP from it?
I'm limited to using Windows API's to accomplish this (no 3rd party API's)
You can use a library like curl or curlpp to get the content of http://myexternalip.com/raw . Its response is only your external ip, you can read and use it.
Here is the winsock way. It simply extracts the IP address embedded in the HTML code that the server sent.
This code uses http://api.ipify.org/ .
Below are two different codes. One for VS2012-2015 that uses
strcpy_s( )
and one for Visual C++ 6.0 that usesstrcpy( )
, because VS2012-2015 throws an error message prompting you to usestrcpy_s( )
instead ofstrcpy( )
.Visual Studio 2012-2015 code.
Visual C++ 6.0 code
This has nothing to do with C++ or any language in particular.
Furthermore, knowing the address of your router won't do you much good, you will know it's NAT address, not it's external address, and it is also possible your router is not the last router on the way out to the internet.
You must use an external entity - usually a webservice of some sort that will report the IP address of the router that contacted it.
Here is a sample question of someone asking how to get the client IP address in PHP.
In theory, you can use the Windows uPnP API to do this. You'd start by using the
UPnPDeviceFinder
to enumerate Internet Gateway Devices. Then you get anIUPnPRemoteEndpointInfo
for the gateway (well, there's usually only one, anyway) and invoke itsGetStringValue
, passing a string containing"RemoteAddress"
to get its remote address (which I think means its external address, though I'll admit I'm not entirely certain). Oh, and since this is COM, that has to be a system string, not a normal string.Getting the IP from an external provider is a lot easier. Without using any 3rd party libraries, code for it looks like this:
compiled with:
Note: if your machine is configured to use IPv6, this can (and will) retrieve your IPv6 address).