java 如何成功获取外部IP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10322506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:34:02  来源:igfitidea点击:

How to get external IP successfully

javaip

提问by o f

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

阅读后:在Java中获取“外部”IP地址

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?

我认为这是因为服务器响应速度不够快,有没有办法确保它会获得外部 ip?

EDIT: okay so its getting rejected, anyone else know of another site that can do the same function

编辑:好的,所以它被拒绝了,其他人知道另一个可以执行相同功能的网站

回答by Sourav301

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

回答by Justin

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

在运行以下代码之前,请先看看这个: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);
}

回答by Adam Gent

While playing with Go I saw your question. I made a quick App on Google App Engine using Go:

在玩围棋时,我看到了您的问题。我使用 Go 在 Google App Engine 上制作了一个快速应用程序:

Hit this URL:

点击这个网址:

http://agentgatech.appspot.com/

http://agentgatech.appspot.com/

Java code:

爪哇代码:

new BufferedReader(new InputStreamReader(new URL('http://agentgatech.appspot.com').openStream())).readLine()

Go code for the app which you can copy and make your own app:

为应用程序编写代码,您可以复制并制作自己的应用程序:

package hello

import (
    "fmt"
    "net/http"
)

func init() {
    http.HandleFunc("/", handler)
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, r.RemoteAddr)
}

回答by Brian

We've set up CloudFlareand as designed they're challenging unfamiliar useragents. If you can set your UA to something common, you should be able to gain access.

我们已经设置CloudFlare并按照设计它们正在挑战不熟悉的用户代理。如果您可以将您的 UA 设置为常见的内容,您应该能够获得访问权限。

回答by duskwuff -inactive-

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

403 响应表明服务器由于某种原因明确拒绝您的请求。有关详细信息,请联系 WhatIsMyIP 的运营商。

回答by duskwuff -inactive-

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.

某些服务器具有阻止“非浏览器”访问的触发器。他们知道您是某种可以进行DOS 攻击的自动应用程序。为避免这种情况,您可以尝试使用 lib 访问资源并设置“浏览器”标头。

wget works in this way:

wget 以这种方式工作

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

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

使用 Java,您可以使用HttpClient 库并设置“User-Agent”标头。查看“要尝试的事情”部分的主题 5。

Hope this can help you.

希望这可以帮到你。

回答by N Czar

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

使用 AWS 上的检查 IP 地址链接对我有用。请注意,还要添加 MalformedURLException,IOException

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

回答by Baran

You can use another web service like this; http://freegeoip.net/static/index.html

您可以像这样使用另一个 Web 服务;http://freegeoip.net/static/index.html

回答by Someone Somewhere

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)

这就是我使用 rxJava2 和 Butterknife 的方式。您会希望在另一个线程中运行网络代码,因为在主线程上运行网络代码会出现异常!我使用 rxJava 而不是 AsyncTask,因为当用户在线程完成之前移动到下一个 UI 时,rxJava 会很好地清理。(这对于非常繁忙的 UI 非常有用)

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

更新- 我发现 URLConnection 真的很糟糕;得到结果需要很长时间,不是真的超时等等。下面的代码改善了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;
}