3 回答

TA贡献1796条经验 获得超10个赞
由于机器可能有多个地址,因此很难确定哪个地址适合您。通常,您希望系统根据其路由表分配IP。由于结果取决于您要连接的IP,因此有一个简单的技巧:只需创建一个连接,然后查看您从操作系统获得的地址即可:
// output on my machine: "192.168.1.102"
Socket s = new Socket("192.168.1.1", 80);
System.out.println(s.getLocalAddress().getHostAddress());
s.close();
// output on my machine: "127.0.1.1"
System.out.println(InetAddress.getLocalHost().getHostAddress());
我不确定是否可以在不建立连接的情况下执行此操作。我认为我曾经设法用Perl(或C?)做到这一点,但是不要问我有关Java的问题。我认为可能无需实际连接即可创建UDP套接字(DatagramSocket)。
如果途中有NAT路由器,您将无法获得远程主机可以看到的IP。但是,以您给出的192. *为例,我认为您不在乎。

TA贡献1906条经验 获得超10个赞
这是避免IPv6和环回结果的方法。
public InetAddress getCurrentIp() {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) networkInterfaces
.nextElement();
Enumeration<InetAddress> nias = ni.getInetAddresses();
while(nias.hasMoreElements()) {
InetAddress ia= (InetAddress) nias.nextElement();
if (!ia.isLinkLocalAddress()
&& !ia.isLoopbackAddress()
&& ia instanceof Inet4Address) {
return ia;
}
}
}
} catch (SocketException e) {
LOG.error("unable to get current IP " + e.getMessage(), e);
}
return null;
}
添加回答
举报