3

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

代码:

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

我以为我是赢家,但我收到以下错误

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)

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

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

4

9 回答 9

12
    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);
     }
于 2013-09-26T16:22:53.673 回答
8

在运行以下代码之前,请先查看: 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);
}
于 2012-04-25T20:39:59.453 回答
8

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

点击这个网址:

http://agentgatech.appspot.com/

Java代码:

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

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

package hello

import (
    "fmt"
    "net/http"
)

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

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, r.RemoteAddr)
}
于 2012-04-25T21:00:33.513 回答
4

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

wget 以这种方式工作:

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

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

希望这可以帮到你。

于 2012-04-25T19:45:34.910 回答
3

403 响应表明服务器出于某种原因明确拒绝您的请求。详情请联系 WhatIsMyIP 的运营商。

于 2012-04-25T19:35:30.110 回答
3

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

于 2012-05-01T14:10:49.617 回答
2

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

于 2012-04-25T19:36:35.840 回答
2

使用 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;
}
于 2016-05-26T17:35:45.257 回答
0

这就是我使用 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;
    }
}

更新- 我发现 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;
}
于 2018-05-06T20:55:34.987 回答