我如何才能找到该地址的网络部分保留的位数?
这是我在Java代码:
public static void main(String[] args) throws SocketException {
Enumeration<NetworkInterface> ifaces;
ifaces = NetworkInterface.getNetworkInterfaces();
while (ifaces.hasMoreElements()) {
NetworkInterface iface = ifaces.nextElement();
System.out.println(iface);
// loop through all of the (potential) IP addresses configured to use "iface"
Enumeration<InetAddress> addresses = iface.getInetAddresses();
// Showing teh value, either ipv4 or ipv6
// and the number of bits reserved for the network portion of the address
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
String hostAddress = address.getHostAddress();
System.out.println("addr: " + address.);
if (address instanceof Inet4Address && !address.isLoopbackAddress()) {
System.out.println("IPv4: /" + hostAddress);
}
else if(address instanceof Inet6Address && !address.isLoopbackAddress()){
System.out.println("IPv6: /" + hostAddress);
}
}
}
}
输出的例子,我应该得到:
name:lo0 (lo0)
IPv6: /fe80:0:0:0:0:0:0:1%lo0, 64 bits reserved for the network
IPv6: /0:0:0:0:0:0:0:1%lo0, 128 bits reserved for the network
IPv4: /127.94.0.1, 8 bits reserved for the network
IPv4: /127.0.0.1, 8 bits reserved for the network
我如何获得每个MAC地址保留位数?
IP地址和MAC地址是两回事。
你想要的东西,你就需要为每个IP地址对应的子网掩码。这会告诉你一个IP位是网络部分。然而,你不能从一个InetAddress
子网掩码,所以尽量使用NetworkInterface.getInterfaceAddresses()
代替。 InterfaceAddress
有getAddress()
和getNetworkPrefixLength()
方法:
返回此地址的InetAddress。
返回此地址的网络前缀长度。这也被称为IPv4地址的情况下子网掩码。典型的IPv4值将是8(255.0.0.0),16(255.255.0.0)或24(255.255.255.0)。
典型的IPv6值将是128(:: 1/128)或10(FE80 :: 203:BAFF:FE27:1243年至1210年)