为什么这不会返回IP地址?

2 java runtime

除了nullip之外,我不能让它返回任何东西.我必须在格式化String数组中的操作的方式中遗漏一些东西,请帮忙!另外,Java中的命令行工作是否有更好的sdk?更新为了将来参考,这是一个EC2实例,并且执行InetAddress.getLocalHost()会返回null,因此我已经恢复到命令行(AWS SDK对于深入了解本地主机IP来说是一种痛苦).

//要运行的命令: /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;
    }
Run Code Online (Sandbox Code Playgroud)

Joa*_*uer 5

  1. 为什么在使用Java枚举网络接口的简单方法Runtime.exec()时会尝试使用?
  2. 您尝试执行多个命令,将一个命令输出汇总到另一个上.这项工作通常由shell完成.通过直接执行它,您无法获得该功能.您可以通过调用shell并将整个管道作为要执行的参数传递给它来解决这个问题.
  3. 什么时候Runtime.exec()不会.它总结了您在使用时可能遇到的所有主要缺陷Runtime.exec()(包括#2中提到的缺陷)并告诉您如何避免/解决它们.