Question

I am trying to get my program display what the ipconfig command displays in windows. I have managed to get the hostname and the IPv4 address, how can I get IPv6 address and subnet mask? I have tried various things to no avail so far. My code is:

try {
    InetAddress addr = InetAddress.getLocalHost();
    String ipAddr = addr.getHostAddress();
    String hostname = addr.getHostName();
    gsc.mainWindow.printf("Host name: ",hostname,"\n");
    gsc.mainWindow.printf("IP Address: ",ipAddr,"\n");
} catch (Exception e) {
    gsc.mainWindow.printf("Error: ",e,"\n");
}

Consider gsc.mainWindowthe out stream where I print any kind of object. Thanks in advance!

(PS.If anyone can add some tags I can't think of, I will be grateful!)

Was it helpful?

Solution

If you want all of the information ipconfig gives us, I don't think you can get it with the java.net package. If all you are looking for is the IPv6 and IPv4 addresses, then you can use java.net.Inet6Address.getHostAddress()

If you want other information, such as DHCP, default gateway, DNS, then your best bet is to call ipconfig from java and capture the output. This hack is OS specific, so you can also include some code to check the OS before executing.

String os = System.getProperty("os.name");        
try {
    if(os.indexOf("Windows 7")>=0) {
       Process process = Runtime.getRuntime().exec("ipconfig /all");
       process.waitFor();
       InputStream commandOut= process.getInputStream();
       //Display the output of the ipconfig command
       BufferedReader in = new BufferedReader(new InputStreamReader(commandOut));
       String line;
       while((line = in.readLine()) !=null) 
          System.out.println(line);
    }
}
catch(IOException ioe) {    }
catch(java.lang.InterruptedException utoh) {   }        
}

If you want to only display some subset of this information, then inside the while loop you can place some code to look for things like " Host Name" or "Physical Address" and only display the lines containing these strings.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top