Java and Windows 7: Reliability of getting IPv4 netmask?

I ran into a known bug with Java 6 on Windows. I understand that the usual way to get a netmask is to find the length of the network prefix and perform some bit shifts. The problem is that on Windows, the prefix length often returns incorrectly, so we get 128 when we should get 24 or 20.

This solution proposes putting -Djava.net.preferIPv4Stack=true in the Java command line. Unfortunately, in Windows 7, adding this parameter as a VM parameter or on the Java command line has no effect.

(a) Does anyone know of any other issues for this issue that may still work on Windows 7?

(b) Alternatively, is there a completely different way to get a reliable netmask?

Thanks!

PS Here is a bug report related to this .

+6
source share
3 answers

The option -Djava.net.preferIPv4Stack=true VM should work under any OS. Alternatively, it can be placed in Java code as System.setProperty("java.net.preferIPv4Stack","true"); . If, something (a library or something else) does not reset its true state.

+3
source

The code below displays the subnet mask. On a computer with more than one network connection (for example, a laptop with a wireless connection and a Cat-5 Ethernet connection), it can write the subnet mask twice, because there can be two different IP addresses for the client.

  String os = System.getProperty("os.name"); try { if(os.indexOf("Windows 7")>=0) { Process process = Runtime.getRuntime().exec("ipconfig"); process.waitFor(); InputStream commandOut= process.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(commandOut)); String line; while((line = in.readLine()) !=null) { if(line.indexOf("Subnet Mask")>=0) { int colon = line.indexOf(":"); System.out.println(line.substring(colon+2)); } } } catch(IOException ioe) { } catch(java.lang.InterruptedException utoh) { } 

On my laptop with an active wired and wireless connection, I get this output: 255.255.254.0 255.255.254.0

When I turn off my wireless connection, I see only one line of output for the wired Ethernet line, as expected.

+2
source

Since we only have a problem in Windows 7, why not look for a solution for a specific OS? I know that we can run Windows programs with Java, including the Windows command line or bat files. There should be a way to redirect ipconfig output to a text file on Windows. Your program should be able to get the subnet mask by calling ipconfig and then reading the output.

+1
source

Source: https://habr.com/ru/post/908548/


All Articles