Java 获取子网起始和结束IP地址:基于 IP 地址和前缀长度
以下是一个获取起始和结束IP地址的Java方法示例:
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class SubnetUtils {
public static void main(String[] args) {
String subnet = '1111::/4';
String[] parts = subnet.split('/');
String address = parts[0];
int prefixLength = Integer.parseInt(parts[1]);
try {
InetAddress inetAddress = InetAddress.getByName(address);
byte[] byteArray = inetAddress.getAddress();
BigInteger bigInteger = new BigInteger(1, byteArray);
BigInteger subnetMask = BigInteger.valueOf(-1).shiftLeft(128 - prefixLength);
BigInteger startIp = bigInteger.and(subnetMask);
BigInteger endIp = startIp.add(subnetMask.not());
InetAddress startInetAddress = InetAddress.getByAddress(startIp.toByteArray());
InetAddress endInetAddress = InetAddress.getByAddress(endIp.toByteArray());
System.out.println('Start IP: ' + startInetAddress.getHostAddress());
System.out.println('End IP: ' + endInetAddress.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
使用上述代码,可以将子网IP地址分为两个部分:地址和前缀长度。然后,通过将地址转换为InetAddress对象,获取其字节数组,并使用BigInteger类进行处理。通过对起始IP地址进行与操作,并对结束IP地址进行非操作,可以计算出起始和结束IP地址。最后,将字节数组转换回InetAddress对象,即可获取起始和结束IP地址。
原文地址: https://www.cveoy.top/t/topic/ojaQ 著作权归作者所有。请勿转载和采集!