【问题标题】:Test with Java if two IPs are in the same network如果两个 IP 在同一个网络中,请使用 Java 测试
【发布时间】:2012-01-23 06:13:48
【问题描述】:

如何根据子网掩码测试两个IP是否在同一个网络中?

例如,我有 IP 1.2.3.4 和 1.2.4.3:如果掩码为 255.0.0.0 或 255.255.0.0 甚至 255.255.248.0,则两者都在同一个网络中,但如果掩码为 255.255.255.0 则不是。

【问题讨论】:

    标签: java ip subnet


    【解决方案1】:

    试试这个方法:

    public static boolean sameNetwork(String ip1, String ip2, String mask) 
    throws Exception {
    
        byte[] a1 = InetAddress.getByName(ip1).getAddress();
        byte[] a2 = InetAddress.getByName(ip2).getAddress();
        byte[] m = InetAddress.getByName(mask).getAddress();
    
        for (int i = 0; i < a1.length; i++)
            if ((a1[i] & m[i]) != (a2[i] & m[i]))
                return false;
    
        return true;
    
    }
    

    并像这样使用它:

    sameNetwork("1.2.3.4", "1.2.4.3", "255.255.255.0")
    > false
    

    编辑:

    如果您已经将 IP 作为 InetAddress 对象:

    public static boolean sameNetwork(InetAddress ip1, InetAddress ip2, String mask) 
    throws Exception {
    
        byte[] a1 = ip1.getAddress();
        byte[] a2 = ip2.getAddress();
        byte[] m = InetAddress.getByName(mask).getAddress();
    
        for (int i = 0; i < a1.length; i++)
            if ((a1[i] & m[i]) != (a2[i] & m[i]))
                return false;
    
        return true;
    
    }
    

    【讨论】:

    • 不错的解决方案 - 避免自己解析字符串。
    • 我已经将 IP 本身作为 InetAddresses,所以最多我必须解析掩码。
    • @xZise 我编辑了我的答案以匹配您的最后评论。请注意,如果所有比较的掩码都相同,最好只计算一次它的 byte[] 地址并重用它
    【解决方案2】:

    很简单:mask &amp; ip1 == mask &amp; ip2 - 您必须将 IP 全部解释为一个数字,但这应该很明显。

    【讨论】:

    • @xZise 掩码是您的子网掩码。并且确保它同样适用于 IPv6 - 与 IPv4 相比只是一种不同的表示法。但最后你只是使用子网掩码来屏蔽IP的网络部分,然后相互比较。
    • 但是如何从程序本身获取子网掩码呢?
    • @xZise 对不起,我不明白你的问题。您是否想要最具体的子网掩码以便 2 个 IP 在同一个网络中?在没有子网掩码的任何其他情况下,您根本无法回答 2 个 IP 是否在同一个网络中的问题(这毕竟取决于掩码)。
    • 而且不问用户就没有办法确定子网掩码吗?
    • @xZise 我不认为 InetAddress 存储该信息,但即使它存储了 - 它从哪里获取信息本身?您需要以一种或另一种方式从用户那里获取该信息(以及她的配置 - 如果它是本地进程,您可以从操作系统读取信息)无法解决。
    【解决方案3】:

    此解决方案也适用于 IPv4/IPv6。

    static boolean sameNetwork(final byte[] x, final byte[] y, final int mask) {
        if(x == y) return true;
        if(x == null || y == null) return false;
        if(x.length != y.length) return false;
        final int bits  = mask &   7;
        final int bytes = mask >>> 3;
        for(int i=0;i<bytes;i++)  if(x[i] != y[i]) return false;
        final int shift = 8 - bits;
        if(bits != 0 && x[bytes]>>>shift != y[bytes]>>>shift) return false;
        return true;
    }
    static boolean sameNetwork(final InetAddress a, final InetAddress b, final int mask) {
        return sameNetwork(a.getAddress(), b.getAddress(), mask);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 2019-01-19
      • 2014-08-05
      • 1970-01-01
      • 2023-01-05
      相关资源
      最近更新 更多