What is the best way to get IP address in Java? I was trying getLocalHost()
, but it returns my computer IP addrees. I want something like this.
Also I was trying to get IP by HTML from services like that, but I think it's not good idea.

- 485
- 2
- 7
- 13
-
2check this out: http://stackoverflow.com/questions/9481865/how-to-get-ip-address-of-our-own-system-using-java – Joseph Pla Aug 15 '13 at 14:28
-
@Joey this post is about a client that is connected trough PPP in the client computer, so it have the public IP available on the machine. The last answer is what it says, calling a external service to get the IP. – Diego C Nascimento Aug 15 '13 at 14:39
2 Answers
The following uses Amazon web services and works for me.
import java.net.*;
import java.io.*;
public class IPTest{
public static void main(String args[]) throws Exception{
URL whatismyip = new URL("http://checkip.amazonaws.com/");
BufferedReader in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));
String ip = in.readLine(); //you get the IP as a String
System.out.println("My IP address:"+ip);
}
}

- 950
- 1
- 11
- 27
You want to get your internet (someone will call public, I don't totally agree on that term) ip address. Basically you have two options, or call an external service (it does not need to be a site like that, it can be a STUN, or anything made for that), or you can get it from your modem/router/NAT.
You could use UPnP if enabled in the device, this is a good approach.
Other option is instead of trying to parse or get the results from an external service, you get it from your device web page, some devices even not need admin rights to get that information, so you only need to parse the page for the information.
Most of the answers just say you to use an external service, like you said its not a good idea. In my opniation its not the best one, because you be dependent on an external service provider. If it changes anything you need to change too, as if they get the service broken.
So, if you can implement in your own LAN its better, just not easier.

- 2,801
- 1
- 17
- 23