Java 为网络预留的位

Java 为网络预留的位,java,sockets,network-interface,Java,Sockets,Network Interface,如何找到为地址的网络部分保留的位数 以下是我的java代码: public static void main(String[] args) throws SocketException { Enumeration<NetworkInterface> ifaces; ifaces = NetworkInterface.getNetworkInterfaces(); while (ifaces.hasMoreElements()) { Networ

如何找到为地址的网络部分保留的位数

以下是我的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);
            }

        }

    }
}

如何获得每个mac地址的保留位数?

IP地址和mac地址是两个不同的东西

为了满足您的需要,您需要为每个IP地址提供相应的子网掩码。这将告诉您IP的哪些位用于网络部分。但是,您无法从
InetAddress
获取子网掩码,因此请尝试使用。方法:

返回此地址的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)

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