在 Java 中获取局域网内其他机器的 IP 地址可以使用 InetAddress
类。使用 InetAddress.getLocalHost()
方法获取本机的 IP 地址,通过调用 InetAddress.getAllByName(String host)
方法可以获取指定主机名的所有 IP 地址。例如:
InetAddress localHost = InetAddress.getLocalHost();
System.out.println("本机 IP: " + localHost.getHostAddress());
InetAddress[] addresses = InetAddress.getAllByName("192.168.1.1");
for (InetAddress address : addresses) {
System.out.println("局域网内其他机器 IP: " + address.getHostAddress());
}
要获取公网 IP 地址,可以向一些公开的 IP 查询服务发送 HTTP 请求,解析返回的响应。例如使用 HttpURLConnection
类发送 GET 请求到 http://api.ipify.org
:
URL url = new URL("http://api.ipify.org");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String publicIp = in.readLine();
System.out.println("公网 IP: " + publicIp);
}
除使用第三方服务,你也可以尝试其他方法,如使用 SocketAddress
类连接一个公开的 IP 地址服务器。