Getting the 'external' IP address in Java

前端 未结 12 1824
自闭症患者
自闭症患者 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条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 15:46

    How about this? It's simple and worked the best for me :)

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    
    public class IP {
        public static void main(String args[]) {
            new IP();
        }
    
        public IP() {
            URL ipAdress;
    
            try {
                ipAdress = new URL("http://myexternalip.com/raw");
    
                BufferedReader in = new BufferedReader(new InputStreamReader(ipAdress.openStream()));
    
                String ip = in.readLine();
                System.out.println(ip);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

提交回复
热议问题