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



我想从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 范围的 from 和 to 地址,请执行以下操作:

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值最终出错。我会把它留给你一个练习来解决这个问题。

开源 IPAddress Java 库将以多态方式为 IPv4 和 IPv6 执行此操作。 免责声明:我是该库的项目经理。

IPAddress addr = new IPAddressString("192.168.1.1/24").getAddress().toPrefixBlock();
System.out.println(addr.getLower() + " - " + addr.getUpper());

输出:

192.168.1.0/24 - 192.168.1.255/24

最新更新