Detecting Wide Area Network(WAN) IP programmatically
This is a reliable way to detect WAN IP address from Java, cpp or any other programming language. Motivation for this was my need to update my DNS server automatically, presented code will be in Java I have decided to use Java for cross-platform support and its my favorite language, in near feature I will include cpp code as well(moding Linksys router to Support xname.org Free DNS service)
Intro
There are couple ways of detecting an WAN IP address that I know of, first one is to use ping utility with hop count of 1 then parse the results
Z:\>ping -r 1 www.google.com
Pinging www.l.google.com [64.233.167.147] with 32 bytes of data:
Request timed out.
drawback of this approach is that it is dependent on ping utility and is not cross platform compatible. The second strategy is to use some external service that will
echo back us our ip address like http://www.whatismyip.com/ problem with this approach is that if service is down we want be able to retrieve our IP.
Strategy
I decided to go with second option using external service, to overcome the possibility of service being down I have assembled list of number of free Ip detection services using Goggle. Next step was to parse the page and extract the IP address, here came up another problem, some of the services contained multiple IP’s. My solution was to query my services while the number of top IP count was less than a set threshold.
Code
I am using regular expressions to extract all the IP from retrieved page.
Regex Here