1

I'm writing because I've some problems finding a correct SubnetMask of my own PC. I've already read the question 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?

Community
  • 1
  • 1
Wallkan
  • 480
  • 1
  • 8
  • 27

1 Answers1

2

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
Suroot
  • 4,315
  • 1
  • 22
  • 28
  • Your method answer me: /fe80:0:0:0:e416:af9b:f0b9:f57f%10/64 /192.168.1.2/128 – Wallkan Jul 02 '11 at 13:49
  • Yes, which is the point I was making. NetworkInterface.getByInetAddress() will return the interface (which in most instances can support both ipv6 as well as ipv4). I find it interesting that 192.168.1.2 gives you a /128 (this should be listed by the ::1 ipv6 address). I'm not quite understanding how you're getting /128 for an IPv4 address. – Suroot Jul 02 '11 at 14:16
  • I'm not understanding it to! This is my problem! I can't find anywhere 255.255.255.240 or 16 – Wallkan Jul 02 '11 at 22:18
  • I updated with the output that I get when I run that snippit of code in its own main(). – Suroot Jul 02 '11 at 22:26
  • For me also the list size -1th element returns the ipv4 value. So i have used the last element for my requirement. Did you find any other way for this? – Sash_KP Mar 11 '23 at 13:32