为什么不返回 IP 地址?

发布于 2024-10-19 02:08:05 字数 1033 浏览 2 评论 0原文

除了 ip 的 null 之外,我无法让它返回任何内容。我在格式化字符串数组内的操作时一定遗漏了一些东西,请帮忙!另外,是否有更好的用于 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;
    }

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;
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

清引 2024-10-26 02:08:05
  1. 当存在 在 Java 中枚举网络接口的简单方法
  2. 您尝试执行多个命令,将一个命令的输出通过管道传输到另一个命令上。这项工作通常由 shell 完成。通过直接执行它,您无法获得该功能。您可以通过调用 shell 并将整个管道作为要执行的参数传递给它来解决这个问题。
  3. 阅读Runtime.exec()获胜时't。它总结了使用 Runtime.exec() 时可能陷入的所有主要陷阱(包括 #2 中提到的陷阱),并告诉您如何避免/解决它们。
  1. Why do you try to use Runtime.exec() when there's a perfectly easy way to enumerate network interfaces in Java?
  2. You try to execute multiple commands, piping one commands output onto the other one. That job is usually done by the shell. By directly executing it, you don't get that feature. You can work around that fact by invoking the shell and passing the whole pipe to it as an argument to be executed.
  3. Read When Runtime.exec() won't. It summarizes all major pitfalls you can fall into when using Runtime.exec() (including the one mentioned in #2) and tells you how to avoid/solve them.
失去的东西太少 2024-10-26 02:08:05
    StringBuilder result = new StringBuilder()

    try {
        while ((ls_str = ls_in.readLine()) != null) {
            result.append(ls_str);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return result.toString();
    StringBuilder result = new StringBuilder()

    try {
        while ((ls_str = ls_in.readLine()) != null) {
            result.append(ls_str);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return result.toString();
那支青花 2024-10-26 02:08:05

如果将数组传递给 exec(),则它的作用就好像第一个之后的所有元素都是第一个元素的参数。 “awk”不是 ifconfig 的有效参数。

If you pass an array to exec(), it acts as if all the elements after the first are arguments to the first one. "awk" is not a valid argument to ifconfig.

自此以后,行同陌路 2024-10-26 02:08:05

采用 String[]Runtime.exec() 形式不会在管道中执行多个命令。相反,它执行带有附加参数的单个命令。我认为完成您想要的操作的最简单方法是 exec shell 来执行管道:

Runtime.getRuntime().exec(new String[] { 
    "bash", "-c", "/sbin/ifconfig | awk 'NR==2{print$2}' | sed 's/addr://g'"
});

The form of Runtime.exec() which takes a String[] does not execute multiple commands in a pipeline. Rather it executes a single command with additional arguments. I think the easiest way to do what you want is to exec a shell to do the pipeline:

Runtime.getRuntime().exec(new String[] { 
    "bash", "-c", "/sbin/ifconfig | awk 'NR==2{print$2}' | sed 's/addr://g'"
});
静谧 2024-10-26 02:08:05

您可以使用java.net.NetworkInterface。像这样:

public static List<String> getIPAdresses() {
    List<String> ips = new ArrayList<String>();
    try {
        Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();

        while (e.hasMoreElements()) {
            NetworkInterface ni = e.nextElement();

            Enumeration<InetAddress> e2 = ni.getInetAddresses();

            while (e2.hasMoreElements()) {
                InetAddress ip = e2.nextElement();
                if (!ip.isLoopbackAddress())
                    ips.add(ip.getHostAddress());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ips;
}

Joachim Sauer 已经发布了 文档链接

You can use java.net.NetworkInterface. Like this:

public static List<String> getIPAdresses() {
    List<String> ips = new ArrayList<String>();
    try {
        Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();

        while (e.hasMoreElements()) {
            NetworkInterface ni = e.nextElement();

            Enumeration<InetAddress> e2 = ni.getInetAddresses();

            while (e2.hasMoreElements()) {
                InetAddress ip = e2.nextElement();
                if (!ip.isLoopbackAddress())
                    ips.add(ip.getHostAddress());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ips;
}

Joachim Sauer already posted the link to the documentation

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文