如何检查IP地址是否是多宿主系统上的本地主机? [英] How to check if an IP address is the local host on a multi-homed system?

查看:186
本文介绍了如何检查IP地址是否是多宿主系统上的本地主机?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于具有多个NIC卡的计算机,Java中是否有方便的方法来告知给定的IP地址是否是当前计算机。例如。

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.

boolean IsThisMyIpAddress("192.168.220.25");


推荐答案

如果您要查找任何有效的IP地址对于本地主机,您必须检查特殊的本地主机(例如127.0.0.1)地址以及分配给任何接口的地址。例如......

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...

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();
}

这篇关于如何检查IP地址是否是多宿主系统上的本地主机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆