views:

477

answers:

5

Hi

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.

Any help would be appreciated.

Thanks.

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;
}

}

+10  A: 

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.

Edit:

The other answers pointed out to the whatismyip.com website, I found out that they have a link that you can scrap the IP from, here is some Java code I put together to do it:

import java.net.*;
import java.io.*;

URL whatismyip = new URL("http://www.whatismyip.com/automation/n09230945.asp");
BufferedReader in = new BufferedReader(new InputStreamReader(
                whatismyip.openStream()));

String ip = in.readLine(); //you get the IP as a String
System.out.println(ip);
Bakkal
this is fantastic! nice answer.
Uncle
+3  A: 

Make a HttpURLConnection to some site like www.whatismyip.com and parse that :-)

nc3b
+1  A: 

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!

Jack
@Jack: You don't have to parse html. The first line of the webpage source of http://whatismyip.com/ is your external IP.
Martijn Courteaux
+1  A: 

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.

bmargulies
+1  A: 

http://jstun.javawi.de/ will do it - provided your gateway device does STUN )most do)