1

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!)

m4tx
  • 4,139
  • 5
  • 37
  • 61
Angelos Chalaris
  • 6,611
  • 8
  • 49
  • 75
  • Duplicate of: http://stackoverflow.com/questions/6908398/inetaddress-gethostaddress-ipv6-compliant and http://stackoverflow.com/questions/1221517/how-to-get-subnet-mask-using-java – m4tx Sep 09 '12 at 12:12
  • The second post doesn't work at all for me... :/ The first post is something I think I overlooked, I am sorry... – Angelos Chalaris Sep 09 '12 at 12:13
  • 3
    Maybe this one will work for you: http://stackoverflow.com/questions/6557275/obtaining-an-ipv4-subnetmask-with-java :) – m4tx Sep 09 '12 at 12:15
  • Ok I tried it out and it returns my IPv6 address based on what my `ipconfig` says... I think the second post was about the subnet mask... :P – Angelos Chalaris Sep 09 '12 at 12:21
  • Why are you trying to reproduce something for which there is already a solution? – user207421 Sep 10 '12 at 02:40

1 Answers1

1

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.

Thorn
  • 4,015
  • 4
  • 23
  • 42