使用Java获取ipv4子网掩码

使用Java获取ipv4子网掩码,java,mask,subnet,Java,Mask,Subnet,我写这篇文章是因为我在寻找自己电脑的正确子网掩码时遇到了一些问题。 我已经读过这个问题,但如果我尝试: InetAddress thiscomputer = InetAddress.getLocalHost(); NetworkInterface thisNetworkInterface = NetworkInterface.getByInetAddress(thiscomputer); int thiscomputerSubnetMask = thisNetworkInterface.getI

我写这篇文章是因为我在寻找自己电脑的正确子网掩码时遇到了一些问题。 我已经读过这个问题,但如果我尝试:

InetAddress thiscomputer = InetAddress.getLocalHost();
NetworkInterface thisNetworkInterface = NetworkInterface.getByInetAddress(thiscomputer);
int thiscomputerSubnetMask = thisNetworkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength();
System.out.println("This pc subnetmask: "+thiscomputerSubnetMask);
它将写64。对象
thisNetworkInterface.getInterfaceAddresses()
只有一个元素,它是128

现在,我正在寻找一个可以在ipv4协议中使用的数字,我的实际子网掩码是255.255.255.240,所以我在寻找一个16(256-240),但我无法从我知道的方法中获得它

我甚至不明白64或128代表什么!
有人能帮我吗?

使用下面的代码查看/64中的地址(答案会让你感到惊讶)。答案是.getInterfaceAddresses().get(0)不可扩展,可能不会返回您一直期望的答案

InetAddress localHost = Inet4Address.getLocalHost();
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);

for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
    System.out.println(address.getAddress() + "/" + address.getNetworkPrefixLength());
}
编辑:这是我的机器(Mac)的输出


也许你正在使用ipv6的东西..+你没有使用相同的类你的方法回答我:/fe80:0:0:e416:af9b:f0b9:f57f%10/64/192.168.1.2/128是的,这就是我要说的。NetworkInterface.getByInetAddress()将返回接口(在大多数情况下,该接口可以同时支持ipv6和ipv4)。我发现192.168.1.2为您提供了一个/128(应该按::1 ipv6地址列出)。我不太明白你是如何得到IPv4地址的/128的。我不明白!这是我的问题!我找不到255.255.255.240或16I更新的任何地方,这些都是我在自己的main()中运行那一段代码时得到的输出。
/fe80:0:0:0:5ab0:35ff:fe6e:cdc3%6/64
/172.31.255.21/28