[英]How to get Subnet from an IP in Java
How do I get the subnet value from an IP Address. 如何从IP地址获取子网值。 For eg, we can do below in Python.
例如,我们可以在Python中执行以下操作。 (But how about Java?)
(但是Java呢?)
interface = ipaddress.IPv4Interface('11.22.104.0/0.0.0.255')
value = interface.with_prefixlen
Output of value = 11.22.104.0/24 输出值= 11.22.104.0/24
Basically, I need a function to convert 0.0.0.255 into /24. 基本上,我需要一个函数将0.0.0.255转换为/ 24。 Thanks.
谢谢。
Edit 编辑
-Java 7 is used. -使用Java 7。
With Guava: 用番石榴:
int slash = Integer.bitCount(
~Ints.fromByteArray(
InetAddresses.forString("0.0.0.255").getAddress()));
With Java 8: 使用Java 8:
int slash = Arrays.stream("0.0.0.255".split("\\."))
.mapToInt(Integer::parseInt)
.map(i -> ~i & 0xFF)
.map(Integer::bitCount)
.sum();
With Java 7: 使用Java 7:
int slash = 0;
for (String octet : "0.0.0.255".split("\\.")) {
slash += Integer.bitCount(~Integer.parseInt(octet) & 0xFF);
}
The value of slash
will be 24. slash
的值为24。
The IPAddress Java library supports both IPv4 and IPv6 subnets in a polymorphic manner. IPAddress Java库以一种多态的方式支持IPv4和IPv6子网。 Disclaimer: I am the project manager.
免责声明:我是项目经理。 The following code will convert a host mask to a prefix length:
以下代码会将主机掩码转换为前缀长度:
IPAddressString maskString = new IPAddressString("0.0.0.255");
IPAddress mask = maskString.toAddress();
Integer prefLen = mask.getBlockMaskPrefixLength(false);//24
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.