Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a java program decide which command to execute depending of os

Tags:

java

I have to make a program which will print the network settings using "ipconfig" for Windows and "ifconfig" for Linux, but I need to do that with a unique implementation for both OS.

like image 416
jboy Avatar asked Oct 23 '10 21:10

jboy


4 Answers

You can get the name of the operating system through

System.getProperty("os.name")

Have a look at this page for some sample code.


If it's by any chance the IP of the local host you're interested in, there are ways to get this directly in Java:

  • Getting the IP Address and Hostname of the Local Machine
  • Get the workstation name/ip

There is no way to determine what the "show ip information"-command is for an arbitrary operating system. You will have to hard-code what the command is (if the is one) for each operating system name manually.

like image 74
aioobe Avatar answered Nov 01 '22 04:11

aioobe


As a complement to the other answers, I'll mention SystemUtils from Commons Lang which exposes various constant such as IS_OS_UNIX, IS_OS_WINDOWS, etc.

like image 44
Pascal Thivent Avatar answered Nov 01 '22 05:11

Pascal Thivent


Building on aioobe's solution:

final String osname = System.getProperty("os.name").toLowerCase();
String processName;
if(osname.startsWith("win"))
    processName="ipconfig /some /parameter";
else
    processName="ifconfig -some -parameter";
Runtime.getRuntime().exec(processName);
like image 3
Sean Patrick Floyd Avatar answered Nov 01 '22 05:11

Sean Patrick Floyd


For reference, here's a concrete example that sets a property only for a particular OS:

if (System.getProperty("os.name").startsWith("Mac OS X")) {
    System.setProperty("apple.awt.graphics.UseQuartz", "true");
}
like image 3
trashgod Avatar answered Nov 01 '22 03:11

trashgod