java - 将 CIDR 表示法转换为 IP 范围,无需其他库

标签 java binary byte subnet

我想从 CIDR 中查找 IP 范围。 例如,我输入“192.168.1.1/24”。 如何在 Java 中计算 IP 范围?

我只能将IP地址和子网掩码更改为byte[]。 但我不知道如何合并它们。 这是我的代码。

String str = "192.168.1.1/24";
String[] cidr = str.split("/");
String[] buf = cidr[0].split(".");
byte[] ip = new byte[] { 
                (byte)Integer.parseInt(buf[0]), (byte)Integer.parseInt(buf[1]),(byte)Integer.parseInt(buf[2]), (byte)Integer.parseInt(buf[3])
};

int mask = 0xffffffff << (32 - Integer.parseInt(cidr[1]));
        int value = mask;
        byte[] subnet = new byte[] {
                (byte)(value >>> 24), (byte)(value >> 16 & 0xff), (byte)(value >> 8 & 0xff), (byte)(value & 0xff)
        };

最佳答案

您需要做的第一件事是修复正则表达式,因为 . 有特殊含义:cidr[0].split("\\.");

然后,使用按位 AND、OR 和 NOT 构建 IP 范围的起始地址和目标地址:

byte[] from = new byte[4];
byte[] to = new byte[4];
for (int i = 0; i < to.length; i++) {
    from[i] = (byte) (ip[i] & subnet[i]);
    to[i] = (byte) (ip[i] | ~subnet[i]);
}

最后打印结果:

System.out.printf("%d.%d.%d.%d - %d.%d.%d.%d%n",
        Byte.toUnsignedInt(from[0]), Byte.toUnsignedInt(from[1]),
        Byte.toUnsignedInt(from[2]), Byte.toUnsignedInt(from[3]),
        Byte.toUnsignedInt(to[0]), Byte.toUnsignedInt(to[1]),
        Byte.toUnsignedInt(to[2]), Byte.toUnsignedInt(to[3]));

输出

192.168.1.0 - 192.168.1.255
<小时/>

仅供引用: /0 代码失败,因为 mask 值最终错误。我将把它作为练习留给您来解决这个问题。

关于java - 将 CIDR 表示法转换为 IP 范围,无需其他库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62124452/

相关文章:

java - 如何在Anjuta IDE中导入现有的Java项目?

java - HostnameVerifier 与 TrustManager?

java - 如何解决 ClassNotFoundException?

Python - 将两字节字符串作为单字节十六进制字符写入二进制文件

java - "server"上的 stub 是什么,骨架是什么意思?

binary - 如何将 "hello world"写入二进制?

Python - 将二进制解码为 boolean 值

java - 两个明文字符串的异或解密

python - int.from_bytes() 是如何计算的?

c - 通过引用将字节加载到 C 字符串中