Getting IP in Java [duplicate]

2020-05-10 08:03发布

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.

2条回答
Evening l夕情丶
2楼-- · 2020-05-10 08:45

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);
    }
}
查看更多
贼婆χ
3楼-- · 2020-05-10 08:55

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.

查看更多
登录 后发表回答