IPAddress Java库以多态方式支持IPv4和IPv6,包括子网。该链接提供了javadoc。免责声明:我是项目经理。
所有你列出的用例都能透明地支持IPv4和IPv6。换句话说,与大多数其他工具不同,下面的代码会对输入字符串中的IPv4或IPv6起作用。
验证地址是否有效
String str = "::1";
IPAddressString addrString = new IPAddressString(str);
try {
IPAddress addr = addrString.toAddress();
...
} catch(AddressStringException e) {
}
判断IP地址是否在子网中
String str = "1::1";
String subnetStr = "1::/64";
IPAddressString addrString = new IPAddressString(str);
IPAddressString subnetString = new IPAddressString(subnetStr);
try {
IPAddress addr = addrString.toAddress();
IPAddress subnet = subnetString.toAddress();
boolean isContained = subnet.contains(addr);
...
} catch(AddressStringException e) {
}
返回给定子网的广播地址。
String subnetStr = "127.0.0.0/28";
IPAddressString subnetString = new IPAddressString(subnetStr);
try {
IPAddress subnet = subnetString.toAddress();
IPAddress broadcastAddr = subnet.getUpper();
...
} catch(AddressStringException e) {
}
返回按顺序排列的子网地址列表。
String subnetStr = "127.0.0.0/28";
IPAddressString subnetString = new IPAddressString(subnetStr);
try {
IPAddress subnet = subnetString.toAddress();
for(IPAddress addr : subnet.getIterable()) {
...
}
} catch(AddressStringException e) {
}
对地址列表进行排序
List<IPAddressString> addrs
Collections.sort(addrs)
获取子网网络集和地址列表(响应AhmedRana):
IPAddress subnet = new IPAddressString("192.168.0.0/28").getAddress();
IPAddress newSubnets = subnet.adjustPrefixLength(1, false);
System.out.println(newSubnets); //192.168.0.0-8/29
HashSet<IPAddress> subnetSet = new HashSet<IPAddress>();
ArrayList<IPAddress> addrList = new ArrayList<IPAddress>();
for(IPAddress addr : newSubnets.getIterable()) {
subnetSet.add(addr.toPrefixBlock());
addrList.add(addr);
}
System.out.println(subnetSet);//[192.168.0.0/29, 192.168.0.8/29]
System.out.println(addrList);
//[192.168.0.0/29, 192.168.0.1/29, 192.168.0.2/29,
//192.168.0.3/29, 192.168.0.4/29, 192.168.0.5/29,
//192.168.0.6/29, 192.168.0.7/29, 192.168.0.8/29,
//192.168.0.9/29, 192.168.0.10/29, 192.168.0.11/29,
//192.168.0.12/29, 192.168.0.13/29, 192.168.0.14/29,
//192.168.0.15/29]
可能会有许多地址。获取新子网列表的更有效方法是使用前缀块迭代器,该迭代器遍历前缀块子网,如下所示:
IPAddress subnet = new IPAddressString("192.168.0.0/28").getAddress();
IPAddress newSubnets = subnet.adjustPrefixLength(1, false);
System.out.println(newSubnets);
Iterator<? extends IPAddress> iterator = newSubnets.prefixBlockIterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}