I'm not too sure how to go about getting the external IP address of the machine as a computer outside of a network would see it.
My following IPAddress class only gets the local IP address of the machine.
public class IPAddress {
private InetAddress thisIp;
private String thisIpAddress;
private void setIpAdd() {
try {
InetAddress thisIp = InetAddress.getLocalHost();
thisIpAddress = thisIp.getHostAddress().toString();
} catch (Exception e) {
}
}
protected String getIpAddress() {
setIpAdd();
return thisIpAddress;
}
}
The truth is, 'you can't' in the sense that you posed the question. NAT happens outside of the protocol. There is not way for your machine's kernel to know how your NAT box is mapping from external to internal IP addressees. Other answers here offer tricks involving methods of talking to outside web sites.
All this are still up and working smoothly! (as of 19 Dec 2016)
http://curlmyip.com/(17 Dec 2016)Piece of advice: Do not direcly depend only on one of them; try to use one but have a contigency plan considering others! The more you use, the better!
Good luck!
I am not sure if you can grab that IP from code that runs on the local machine.
You can however build code that runs on a website, say in JSP, and then use something that returns the IP of where the request came from:
request.getRemoteAddr()
Or simply use already-existing services that do this, then parse the answer from the service to find out the IP.
Use a webservice like AWS and others
It's not that easy since a machine inside a LAN usually doesn't care about the external IP of its router to the internet.. it simply doesn't need it!
I would suggest you to exploit this by opening a site like http://www.whatismyip.com/ and getting the IP number by parsing the html results.. it shouldn't be that hard!
Make a HttpURLConnection to some site like www.whatismyip.com and parse that :-)
http://jstun.javawi.de/ will do it - provided your gateway device does STUN )most do)