How to get external IP successfully

2019-01-12 01:11发布

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

标签: java ip
9条回答
混吃等死
2楼-- · 2019-01-12 01:53

Using the Check IP address link on AWS worked for me.Please note that MalformedURLException,IOException are to be added as well

public String getPublicIpAddress() throws MalformedURLException,IOException {

    URL connection = new URL("http://checkip.amazonaws.com/");
    URLConnection con = connection.openConnection();
    String str = null;
    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    str = reader.readLine();


    return str;
}
查看更多
手持菜刀,她持情操
3楼-- · 2019-01-12 01:55

A 403 response indicates that the server is explicitly rejecting your request for some reason. Contact the operator of WhatIsMyIP for details.

查看更多
淡お忘
4楼-- · 2019-01-12 01:56

Some servers has triggers that blocks access from "non-browsers". They understand that you are some kind of automatic app that can do a DOS attack. To avoid this, you can try to use a lib to access the resource and set the "browser" header.

wget works in this way:

 wget  -r -p -U Mozilla http://www.site.com/resource.html

Using Java, you can use the HttpClient lib and set the "User-Agent" header. Look the topic 5 of "Things To Try" section.

Hope this can help you.

查看更多
再贱就再见
5楼-- · 2019-01-12 01:57

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);
}
查看更多
Evening l夕情丶
6楼-- · 2019-01-12 01:59

This is how I do it with rxJava2 and Butterknife. You'll want to run the networking code in another thread because you'll get an exception for running network code on the main thread! I use rxJava instead of AsyncTask because the rxJava cleans up nicely when the user moves on to the next UI before the thread is finished. (this is super useful for very busy UI's)

public class ConfigurationActivity extends AppCompatActivity {

    // VIEWS
    @BindView(R.id.externalip) TextInputEditText externalIp;//this could be TextView, etc.

    // rxJava - note: I have this line in the base class - for demo purposes it's here
    private CompositeDisposable compositeSubscription = new CompositeDisposable();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_wonderful_layout);

        ButterKnife.bind(this);

        getExternalIpAsync();
    }

    // note: I have this code in the base class - for demo purposes it's here
    @Override
    protected void onStop() {
        super.onStop();
        clearRxSubscriptions();
    }

    // note: I have this code in the base class - for demo purposes it's here
    protected void addRxSubscription(Disposable subscription) {
        if (compositeSubscription != null) compositeSubscription.add(subscription);
    }

    // note: I have this code in the base class - for demo purposes it's here
    private void clearRxSubscriptions() {
        if (compositeSubscription != null) compositeSubscription.clear();
    }

    private void getExternalIpAsync() {
        addRxSubscription(
                Observable.just("")
                        .map(s -> getExternalIp())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe((String ip) -> {
                            if (ip != null) {
                                externalIp.setText(ip);
                            }
                        })
        );
    }

    private String getExternalIp() {
        String externIp = null;
        try {
            URL connection = new URL("http://checkip.amazonaws.com/");
            URLConnection con = connection.openConnection(Proxy.NO_PROXY);
            con.setConnectTimeout(1000);//low value for quicker result (otherwise takes about 20secs)
            con.setReadTimeout(5000);
            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            externIp = reader.readLine();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return externIp;
    }
}

UPDATE - I've found that URLConnection is really quite shit; it'll take a long time to get a result, not really time out very well, etc. The code below improves the situation with OKhttp

private String getExternalIp() {
    String externIp = "no connection";
    OkHttpClient client = new OkHttpClient();//should have this as a member variable
    try {
        String url = "http://checkip.amazonaws.com/";
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();
        ResponseBody responseBody = response.body();
        if (responseBody != null) externIp = responseBody.string();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return externIp;
}
查看更多
ら.Afraid
7楼-- · 2019-01-12 02:01
    public static void main(String[] args) throws IOException 
    {
    URL connection = new URL("http://checkip.amazonaws.com/");
    URLConnection con = connection.openConnection();
    String str = null;
    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    str = reader.readLine();
    System.out.println(str);
     }
查看更多
登录 后发表回答