I can not get this to return anything but null for ip. I must be missing something in the way that I format the operations inside the String array, please help! Also, is there a better sdk for command line work in Java? Update For future reference, this is an EC2 Instance, and doing an InetAddress.getLocalHost() returns null, so I’ve reverted to the command line (the AWS SDK is kind of a pain just to drill down for a localhost IP).
// Command to be run: /sbin/ifconfig | awk 'NR==2{print$2}' | sed 's/addr://g'
String[] command = new String[] {"/sbin/ifconfig", "awk 'NR==2{print$2}'", "sed 's/addr://g'" };
String ip = runCommand(command);
public static String runCommand(String[] command) {
String ls_str;
Process ls_proc = null;
try {
ls_proc = Runtime.getRuntime().exec(command);
} catch (IOException e1) {
e1.printStackTrace();
}
DataInputStream ls_in = new DataInputStream(ls_proc.getInputStream());
try {
while ((ls_str = ls_in.readLine()) != null) {
return ls_str;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Runtime.exec()when there’s a perfectly easy way to enumerate network interfaces in Java?Runtime.exec()won’t. It summarizes all major pitfalls you can fall into when usingRuntime.exec()(including the one mentioned in #2) and tells you how to avoid/solve them.