如何识别NetworkInterface对象是否为物理NIC

时间:2016-12-25 12:32:59

标签: java network-interface

如何识别NetworkInterface对象是否属于物理网卡,而不是网卡的软件/仿真。

我知道有NetworkInterface#isVirtualNetworkInterface#getParent这样的方法,从理论上讲,它们是否是一个物理接口。

但显然这并没有给我正确的答案,因为当我使用这些方法时,我得到低于o / p,127.0.0.1是一个环回软件界面。

我错过了什么吗?

代码:

 Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
    for (NetworkInterface netIf : Collections.list(nets)) {
        System.out.printf("Display name: %s\n", netIf.getDisplayName());
        System.out.printf("Name: %s\n", netIf.getName());
        System.out.printf("Up? %s\n", netIf.isUp());
        System.out.printf("Loopback? %s\n", netIf.isLoopback());
        System.out.printf("PointToPoint? %s\n", netIf.isPointToPoint());
        System.out.printf("Supports multicast? %s\n", netIf.supportsMulticast());
        System.out.printf("Virtual? %s\n", netIf.isVirtual());
        System.out.printf("Hardware address: %s\n", Arrays.toString(netIf.getHardwareAddress()));
        System.out.printf("MTU: %s\n", netIf.getMTU());
        System.out.printf("Parent: %s\n", netIf.getParent());
        System.out.println("InetAddress:");
        Enumeration<InetAddress> inetAddresses  = netIf.getInetAddresses();
        int count = 1;
        for(InetAddress inetAddress : Collections.list(inetAddresses)){
            System.out.println("\tInetAddress #" + count);
            printInetAddressInfo(inetAddress, "\t\t");
            count++;
        }
        System.out.println("SubInterfaces:");
        displaySubInterfaces(netIf);
        netIf = null;
        System.out.printf("\n");
    }

结果:

Display name: Software Loopback Interface 1
Name: lo
Up? true
Loopback? true
PointToPoint? false
Supports multicast? true
Virtual? false
Hardware address: null
MTU: -1
Parent: null
InetAddress:
    InetAddress #1
        inetAddress: /127.0.0.1
    InetAddress #2
        inetAddress: /0:0:0:0:0:0:0:1
SubInterfaces:

1 个答案:

答案 0 :(得分:1)

  

我错过了什么吗?

我认为问题在于您错误地解释了isVirtual。 javadoc说:

  

public boolean isVirtual()

     

返回此接口是否为虚拟接口(也称为子接口)。在某些系统上,虚拟接口是作为物理接口的子级创建的接口,并且具有不同的设置(如地址或MTU)。通常,接口的名称将是父名称,后跟冒号(:)和标识子项的数字,因为可以有多个虚拟接口连接到单个物理接口。

正如你所看到的,javadoc使用“虚拟接口”来表示与“子接口”相同的东西;即与NIC相关联的第二IP地址。这与任何非物理接口不同。

127.0.0.1实际上是软件环回设备的主要IP地址。这显然是一个非物理设备,但它不是其他主要接口的子接口,无论是物理接口还是虚拟接口。

这有点令人困惑,但在许多与IT相关的背景下,“虚拟”这个词很容易出现。

对于记录,这个“子接口==虚拟接口”命名也不是标准。思科使用“虚拟接口”来表示“Loopback接口,Null接口,子接口或Tunnel接口”;例如http://www.cisco.com/c/en/us/td/docs/ios/12_4/interface/configuration/guide/inb_virt.html#wp1027188

相关问题