Getting IP in Java [duplicate]

穿精又带淫゛_ 提交于 2019-12-20 07:56:00

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/18254848/getting-ip-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!