开发者

Obtaining an ipv4 subnetmask with Java

I'm writing because I've some problems finding a correct SubnetMask of my own PC. I've already read the quest开发者_StackOverflow社区ion How to get subnet mask of local system using java? but if I try:

InetAddress thiscomputer = InetAddress.getLocalHost();
NetworkInterface thisNetworkInterface = NetworkInterface.getByInetAddress(thiscomputer);
int thiscomputerSubnetMask = thisNetworkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength();
System.out.println("This pc subnetmask: "+thiscomputerSubnetMask);

it will write 64. The object thisNetworkInterface.getInterfaceAddresses() has only one more element and it's 128.

Now, I'm looking for a number that can be used in a ipv4 protocol, and my actual subnet mask is 255.255.255.240, so I'm looking for a 16 (256-240), but I can't get it from the methods I know.

Also I don't even understand what 64 or 128 may represent! Can anyone help me?


Use the code below to see what the address is from the /64 (the answer will surprise you). The answer is that .getInterfaceAddresses().get(0) is not extensible and may not return the answer you are expecting all the time.

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

for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
    System.out.println(address.getAddress() + "/" + address.getNetworkPrefixLength());
}

EDIT: Here is the output from my machine (a Mac).

/fe80:0:0:0:5ab0:35ff:fe6e:cdc3%6/64
/172.31.255.21/28
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜