在 Java 中获取“外部”IP 地址

新手上路,请多包涵

我不太确定如何获取机器的外部 IP 地址,因为网络外部的计算机会看到它。

我下面的 IPAddress 类只获取机器的本地 IP 地址。

 public class IPAddress {

    private InetAddress thisIp;

    private String thisIpAddress;

    private void setIpAdd() {
        try {
            InetAddress thisIp = InetAddress.getLocalHost();
            thisIpAddress = thisIp.getHostAddress().toString();
        } catch (Exception e) {
        }
    }

    protected String getIpAddress() {
        setIpAdd();
        return thisIpAddress;
    }
}

原文由 Julio 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 566
2 个回答

我不确定您是否可以从本地计算机上运行的代码中获取该 IP。

但是,您可以构建在网站上运行的代码,比如在 JSP 中,然后使用返回请求来源 IP 的内容:

request.getRemoteAddr()

或者简单地使用执行此操作的现有服务,然后解析服务的答案以找出 IP。

使用 AWS 等网络服务

import java.net.*;
import java.io.*;

URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = new BufferedReader(new InputStreamReader(
                whatismyip.openStream()));

String ip = in.readLine(); //you get the IP as a String
System.out.println(ip);

原文由 bakkal 发布,翻译遵循 CC BY-SA 3.0 许可协议

@stivlo 的评论之一值得作为答案:

您可以使用亚马逊服务 http://checkip.amazonaws.com

 import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class IpChecker {

    public static String getIp() throws Exception {
        URL whatismyip = new URL("http://checkip.amazonaws.com");
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(
                    whatismyip.openStream()));
            String ip = in.readLine();
            return ip;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

原文由 Will 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题