How to get external IP successfully

ip, java

Solution

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

Problem

After reading: Getting the 'external' IP address in Java code: ``` public static void main(String[] args) throws IOException { URL whatismyip = new URL("http://automation.whatismyip.com/n09230945.asp"); BufferedReader in = new BufferedReader(new InputStreamReader(whatismyip.openStream())); String ip = in.readLine(); //you get the IP as a String System.out.println(ip); } ``` I thought I was a winner but I get the following error ``` Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: http://automation.whatismyip.com/n09230945.asp at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at java.net.URL.openStream(Unknown Source) at getIP.main(getIP.java:12) ``` I think this is because the server isnt responding quick enough, is there anyway to ensure that it will get the external ip? EDIT: okay so its getting rejected, anyone else know of another site that can do the same function

Original source

Related problems