【发布时间】:2010-10-23 21:30:52
【问题描述】:
我必须制作一个程序,该程序将使用 Windows 的“ipconfig”和 Linux 的“ifconfig”打印网络设置,但我需要为这两个操作系统使用独特的实现。
【问题讨论】:
标签: java
我必须制作一个程序,该程序将使用 Windows 的“ipconfig”和 Linux 的“ifconfig”打印网络设置,但我需要为这两个操作系统使用独特的实现。
【问题讨论】:
标签: java
可以通过获取操作系统的名称
System.getProperty("os.name")
查看this page 获取一些示例代码。
如果是您感兴趣的本地主机的 IP,可以通过 Java 直接获取:
对于任意操作系统,无法确定“显示 ip 信息”命令是什么。您必须手动为每个操作系统名称硬编码命令是什么(如果是的话)。
【讨论】:
作为对其他答案的补充,我将提到 Commons Lang 的 SystemUtils,它公开了各种常量,例如 IS_OS_UNIX、IS_OS_WINDOWS 等。
【讨论】:
以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);
【讨论】:
作为参考,这里有一个具体的example,它仅为特定操作系统设置属性:
if (System.getProperty("os.name").startsWith("Mac OS X")) {
System.setProperty("apple.awt.graphics.UseQuartz", "true");
}
【讨论】: