在没有其他库的情况下将 CIDR 表示法转换为 IP 范围
Converting CIDR notation into IP range without other library
我想从 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
值最终是错误的。我将把它留作练习,供您解决。
The open-source IPAddress Java library 将以多态方式为 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
我想从 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
值最终是错误的。我将把它留作练习,供您解决。
The open-source IPAddress Java library 将以多态方式为 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