【问题标题】:What does the method getNetInterfaceConfig(String name) of Sigar get when name is null?当name为null时,Sigar的getNetInterfaceConfig(String name)方法得到什么?
【发布时间】:2020-10-28 16:09:03
【问题描述】:

以下代码是什么意思?

String name = sigar.getNetInterfaceConfig(null).getName();
NetInterfaceStat stat = sigar.getNetInterfaceStat(name);

我知道getNetInterfaceConfig(String name)的作用是得到一个具体的NetInterfaceConfig,但是当它的参数为空时它得到了什么?

【问题讨论】:

    标签: java networking sigar


    【解决方案1】:

    我通常建议您使用文档,除了 SIGAR 不再存在。 But you can find it on the Wayback Machine.

    public NetInterfaceConfig getNetInterfaceConfig(java.lang.String name)
                                         throws SigarException 
    

    获取网络接口配置信息。

    不是很有用。可能是一个合理的假设,它将调用委托给无参数方法,这有点帮助。

    public NetInterfaceConfig getNetInterfaceConfig()
                                         throws SigarException 
    

    获取默认网络接口配置信息。迭代 getNetInterfaceList(),返回第一个可用的以太网接口。

    所以有官方的答案。 “第一个可用的以太网接口”。

    要弄清楚这真正意味着什么,请使用源代码。从output of the high level implementation,它声称返回“主要”接口。

    NetInterfaceConfig config = this.sigar.getNetInterfaceConfig(null);
    println("primary interface....." + config.getName());
    

    但是有no such thing as a primary interface。不过,我们可以查看实现以了解 SIGAR 将什么定义为主要的。例如,Windows implementation is hereThe macOS implementation 看起来一模一样。 Linuxinherits from the default here,也一样。

    if (!name) {
        return sigar_net_interface_config_primary_get(sigar, ifconfig);
    }
    

    所以我们可以查看sigar_net_interface_config_primary_get() 的源代码,看看它是如何工作的:

    • 它遍历所有接口
      • 不包括环回接口
      • 不包括没有 IP 地址或没有 MAC 地址的接口
    • 一旦找到上面未排除的接口,就会将该接口作为“主要”返回。

    “第一个”这样的接口是否实际上是“主要”接口是有争议的,如the order they are returned is platform dependent。 “第一个”接口可能是 IPv4 接口,但如果用户通过 IPv6 连接,系统可能会选择不同的接口。或者,您的内部网络与外部网络的接口可能不同。正如路由表所定义的,每一个都是一种流量的“主要”。您可能希望查看您的system's routing tables 以确定您关心的 IP 范围,并将您的网络接口过滤到匹配范围。即使那样,您也可能得到不止一个。例如,在 macOS 上,如果我同时连接有线和无线,我可以更改哪个路由即时接受流量的优先级。

    您的问题的最终答案是,“当名称为null 时,它返回系统发现的第一个不是环回的网络接口,并且具有MAC 地址和IP 地址。”强>

    这可能是也可能不是您正在寻找的界面。

    【讨论】:

    • 这真是太有用了~非常感谢您提供如此专业的答案!
    猜你喜欢
    • 1970-01-01
    • 2013-03-14
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    相关资源
    最近更新 更多