繁体   English   中英

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

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

我无法得到这个,但是为了ip而返回null 我必须在格式化String数组中的操作的方式中遗漏一些东西,请帮忙! 另外,Java中的命令行工作是否有更好的sdk? 更新为了将来参考,这是一个EC2实例,并且执行InetAddress.getLocalHost()会返回null,因此我已经恢复到命令行(AWS SDK只是为了深入了解本地主机IP而感到痛苦)。

//要运行的命令: /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. 为什么在使用Java枚举网络接口的简单方法时,您尝试使用Runtime.exec()
  2. 您尝试执行多个命令,将一个命令输出汇总到另一个上。 这项工作通常由shell完成。 通过直接执行它,您无法获得该功能。 您可以通过调用shell并将整个管道作为要执行的参数传递给它来解决这个问题。
  3. 读取Runtime.exec()时不会 它总结了使用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();

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

采用String[]Runtime.exec()形式不会在管道中执行多个命令。 而是它使用其他参数执行单个命令。 我认为执行所需操作的最简单方法是exec shell来执行管道:

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

您可以使用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已经发布了文档链接

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM