如果要查找对本地主机有效的任何IP地址,则必须检查特殊的本地主机(例如127.0.0.1)地址以及分配给任何接口的地址.例如...
public static boolean isThisMyIpAddress(InetAddress addr) {
// Check if the address is a valid special local or loop back
if (addr.isAnyLocalAddress() || addr.isLoopbackAddress())
return true;
// Check if the address is defined on any interface
try {
return NetworkInterface.getByInetAddress(addr) != null;
} catch (SocketException e) {
return false;
}
}
使用指示端口的字符串,使用以下命令调用:
boolean isMyDesiredIp = false;
try
{
isMyDesiredIp = isThisMyIpAddress(InetAddress.getByName("192.168.220.25")); //"localhost" for localhost
}
catch(UnknownHostException unknownHost)
{
unknownHost.printStackTrace();
}