我不太确定如何获取机器的外部 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;
}
}
我不确定您是否可以从本地计算机上运行的代码中获取该 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)