简体   繁体   English

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

[英]Why does this not return the IP address?

I can not get this to return anything but null for ip. 我无法得到这个,但是为了ip而返回null I must be missing something in the way that I format the operations inside the String array, please help! 我必须在格式化String数组中的操作的方式中遗漏一些东西,请帮忙! Also, is there a better sdk for command line work in Java? 另外,Java中的命令行工作是否有更好的sdk? 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). 更新为了将来参考,这是一个EC2实例,并且执行InetAddress.getLocalHost()会返回null,因此我已经恢复到命令行(AWS SDK只是为了深入了解本地主机IP而感到痛苦)。

// Command to be run: /sbin/ifconfig | awk 'NR==2{print$2}' | sed 's/addr://g' //要运行的命令: /sbin/ifconfig | awk 'NR==2{print$2}' | sed 's/addr://g' /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;
    }
  1. Why do you try to use Runtime.exec() when there's a perfectly easy way to enumerate network interfaces in Java ? 为什么在使用Java枚举网络接口的简单方法时,您尝试使用Runtime.exec()
  2. You try to execute multiple commands, piping one commands output onto the other one. 您尝试执行多个命令,将一个命令输出汇总到另一个上。 That job is usually done by the shell. 这项工作通常由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. 您可以通过调用shell并将整个管道作为要执行的参数传递给它来解决这个问题。
  3. Read When Runtime.exec() won't . 读取Runtime.exec()时不会 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. 它总结了使用Runtime.exec() (包括#2中提到的那个Runtime.exec()时可能遇到的所有主要缺陷,并告诉您如何避免/解决它们。
    StringBuilder result = new StringBuilder()

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

    return result.toString();

If you pass an array to exec(), it acts as if all the elements after the first are arguments to the first one. 如果将数组传递给exec(),它就好像第一个元素之后的所有元素都是第一个元素的参数。 "awk" is not a valid argument to ifconfig . “awk”不是ifconfig的有效参数。

The form of Runtime.exec() which takes a String[] does not execute multiple commands in a pipeline. 采用String[]Runtime.exec()形式不会在管道中执行多个命令。 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: 我认为执行所需操作的最简单方法是exec shell来执行管道:

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

You can use java.net.NetworkInterface . 您可以使用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 Joachim Sauer已经发布了文档链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么getRemoteHost()在部署应用程序时会返回IP地址? - Why does getRemoteHost() return an IP address upon deploying the application? 带有DatagramPacket的getAddress()是否返回可信赖的IP地址? - Does getAddress() with DatagramPacket return a trustworthy IP address? 为什么www.twitter.com有时会使用InetAddress / getHostAddress()返回不同的IP地址? - Why does www.twitter.com return a different IP address sometimes with InetAddress/getHostAddress()? 当我可以 ping IP 地址时,为什么 InetAddress.isReachable 返回 false? - Why does InetAddress.isReachable return false, when I can ping the IP address? InetAddress类getLocalHost()如何返回“首选”IP地址? - How does InetAddress class getLocalHost() return “Preferred” IP address? 为什么UDP打孔不适用于公共IP地址? - Why UDP hole punching does not work for public IP address? Android功能返回IP地址 - Android function to return IP address 为什么我的Java代码返回一个内存地址而不是一个字符串? - Why does my Java code return a memory address and not a string? InetAddress getLocalHost() 未从 C:\WINDOWS\system32\drivers\etc\hosts 返回预期的 IP 地址 - InetAddress getLocalHost() does not return expected IP address from C:\WINDOWS\system32\drivers\etc\hosts getRemoteSocketAddress一起返回url和ip地址 - getRemoteSocketAddress return the url and ip address together
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM