如何找到为地址的网络部分保留的位数?
这是我在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地址保留的位数?
答案 0 :(得分:1)
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/10)