Getting the 'external' IP address in Java

前端 未结 12 1827
自闭症患者
自闭症患者 2020-11-22 15:08

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 g

12条回答
  •  旧时难觅i
    2020-11-22 15:47

    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

    import java.net.*;
    import java.io.*;
    
    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(ip);
    

提交回复
热议问题