Java 如何检查 IP 地址是否是多宿主系统上的本地主机?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2406341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if an IP address is the local host on a multi-homed system?
提问by MItch Branting
For a machine with multiple NIC cards, is there a convenient method in Java that tells whether a given IP address is the current machine or not. e.g.
对于具有多个 NIC 卡的机器,Java 中是否有一种方便的方法可以判断给定的 IP 地址是否是当前机器。例如
boolean IsThisMyIpAddress("192.168.220.25");
采纳答案by Kevin Brock
If you are looking for any IP address that is valid for the local host then you must check for special local host (e.g. 127.0.0.1) addresses as well as the ones assigned to any interfaces. For instance...
如果您正在寻找对本地主机有效的任何 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;
}
}
With a string, indicating the port, call this with:
使用字符串,指示端口,调用它:
boolean isMyDesiredIp = false;
try
{
isMyDesiredIp = isThisMyIpAddress(InetAddress.getByName("192.168.220.25")); //"localhost" for localhost
}
catch(UnknownHostException unknownHost)
{
unknownHost.printStackTrace();
}