How to get external IP successfully

前端 未结 9 1259
耶瑟儿~
耶瑟儿~ 2020-12-03 16:16

After reading: Getting the 'external' IP address in Java

code:

public static void main(String[] args) throws IOException
{
    URL whatismyip         


        
9条回答
  •  Happy的楠姐
    2020-12-03 17:02

    Before you run the following code take a look at this: http://www.whatismyip.com/faq/automation.asp

    public static void main(String[] args) throws Exception {
    
        URL whatismyip = new URL("http://automation.whatismyip.com/n09230945.asp");
        URLConnection connection = whatismyip.openConnection();
        connection.addRequestProperty("Protocol", "Http/1.1");
        connection.addRequestProperty("Connection", "keep-alive");
        connection.addRequestProperty("Keep-Alive", "1000");
        connection.addRequestProperty("User-Agent", "Web-Agent");
    
        BufferedReader in = 
            new BufferedReader(new InputStreamReader(connection.getInputStream()));
    
        String ip = in.readLine(); //you get the IP as a String
        System.out.println(ip);
    }
    

提交回复
热议问题