对于我的情况,我已经重新编写了这样的代码
public static String getIPAddress(String hostname) {
Process process;
String ipAddress = null;
String localIpAddress = null;
String[] commandArray;
if(System.getProperty("os.name").startsWith("Windows")) {
commandArray = new String[] {"cmd", "/c", "ping "+hostname+ " -4 | findstr Pinging"}; // For Windows
} else {
commandArray = new String[] { "bash", "-c", "host "+hostname}; // For Linux and OSX
}
try {
process = Runtime.getRuntime().exec(commandArray);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
String[] output;
// Reading the output of a command executed.
while ((localIpAddress = stdInput.readLine()) != null) {
if(System.getProperty("os.name").startsWith("Windows")) {
output = localIpAddress.split(" ");
ipAddress = output[2].replace("[", "").replace("]", "").trim();
} else {
output = localIpAddress.split("has address");
ipAddress = output[1];
}
}
} catch (IOException e) {
org.owasp.esapi.reference.Log4JLogFactory.getInstance().getLogger(" com.util.esapi.InetAddressWrapper.getIPAddress() << "+e+" >>");
}
return ipAddress;
}