如何找到为地址的网络部分保留的位数?
以下是我的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地址的保留位数?
1条答案
按热度按时间ifmq2ha21#
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)