下面是一些代码来确定应该在多宿主机上工作的本地主机名:
/**
* Work out the first local host name by iterating the network interfaces
*
* @return
* @throws SocketException
*/
private String findFirstLocalHostName() throws SocketException {
Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
while (ifaces.hasMoreElements()) {
NetworkInterface iface = ifaces.nextElement();
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress add = addresses.nextElement();
if (!add.isLoopbackAddress() && add.isSiteLocalAddress()) {
return add.getHostName();
}
}
}
throw new RuntimeException("Failed to determine local hostname");
}
对 isSiteLocalAddress 的调用是否会引入错误?我找不到有关此方法的任何有用信息,但我感觉它仅与 IP v 6 相关并且已被弃用。