java - 如何成功获取外部IP

标签 java ip

看完后:Getting the 'external' IP address in Java

代码:

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?

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

最佳答案

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

关于java - 如何成功获取外部IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10322506/

相关文章:

Java:找出对象的内存大小?

java - 获取无法编译内联过滤器: <Jsonpath with Query>

java - TCP 客户端消息累积

php - 在 PHP 应用程序的 cURL 中强制使用 IPv4

java - 在 Java 中更改本地机器 IP

linux - 从 curl 命令在 shell 脚本中获取正确的输出

java - Java中按字典顺序排列的整数ArrayList的ArrayList

java - 将 InputStream 的内容写入 RichTextItem 并附加到 Java 中的 Notes 文档

ip - 如何允许所有 IP 地址从 Twilio SendGrid 发送电子邮件?

java - 是否可以缩写java函数来删除变量?