官术网_书友最值得收藏!

Using the NetworkInterface class

The NetworkInterface class provides a means of accessing the devices that act as nodes on a network. This class also provides a means to get low-level device addresses. Many systems are connected to multiple networks at the same time. These may be wired, such as a network card, or wireless, such as for a wireless LAN or Bluetooth connection.

The NetworkInterface class represents an IP address and provides information about this IP address. A network interface is the point of connection between a computer and a network. This frequently uses an NIC of some type. It does not have to have a physical manifestation, but it can be performed in software as done with the loopback connection (127.0.0.1 for IPv4 and ::1 for IPv6).

The NetworkInterface class does not have any public constructors. Three static methods are provided to return an instance of the NetworkInterface class:

  • getByInetAddress: This is used if the IP address is known
  • getByName: This is used if the interface name is known
  • getNetworkInterfaces: This provides an enumeration of available interfaces

The following code illustrates how to use the getNetworkInterfaces method to obtain and display an enumeration of the network interfaces for the current computer:

    try {
        Enumeration<NetworkInterface> interfaceEnum = 
            NetworkInterface.getNetworkInterfaces();
        System.out.printf("Name      Display name\n");
        for(NetworkInterface element : 
                Collections.list(interfaceEnum)) {
            System.out.printf("%-8s  %-32s\n",
                    element.getName(), element.getDisplayName());
    } catch (SocketException ex) {
        // Handle exceptions
    }

One possible output is as follows, but it has been truncated to save space:

Name Display name

lo Software Loopback Interface 1

eth0 Microsoft Kernel Debug Network Adapter

eth1 Realtek PCIe FE Family Controller

wlan0 Realtek RTL8188EE 802.11 b/g/n Wi-Fi Adapter

wlan1 Microsoft Wi-Fi Direct Virtual Adapter

net0 Microsoft 6to4 Adapter

net1 Teredo Tunneling Pseudo-Interface

...

A getSubInterfaces method will return an enumeration of subinterfaces if any exist, as shown next. A subinterface occurs when a single physical network interface is divided into logical interfaces for routing purposes:

    Enumeration<NetworkInterface> interfaceEnumeration = 
        element.getSubInterfaces();

Each network interface will have one or more IP addresses associated with it. The getInetAddresses method will return an Enumeration of these addresses. As shown next, the initial list of network interfaces has been augmented to display the IP addresses associated with them:

    Enumeration<NetworkInterface> interfaceEnum = 
        NetworkInterface.getNetworkInterfaces();
    System.out.printf("Name      Display name\n");
    for (NetworkInterface element : 
            Collections.list(interfaceEnum)) {
        System.out.printf("%-8s  %-32s\n",
                element.getName(), element.getDisplayName());
        Enumeration<InetAddress> addresses = 
            element.getInetAddresses();
        for (InetAddress inetAddress : 
                Collections.list(addresses)) {
            System.out.printf("    InetAddress: %s\n", 
                inetAddress);
        }

One possible output is as follows:

Name Display name

lo Software Loopback Interface 1

InetAddress: /127.0.0.1

InetAddress: /0:0:0:0:0:0:0:1

eth0 Microsoft Kernel Debug Network Adapter

eth1 Realtek PCIe FE Family Controller

InetAddress: /fe80:0:0:0:91d0:8e19:31f1:cb2d%eth1

wlan0 Realtek RTL8188EE 802.11 b/g/n Wi-Fi Adapter

InetAddress: /192.168.1.5

InetAddress: /2002:6028:2252:0:0:0:0:1000

InetAddress: /fe80:0:0:0:9cdb:371f:d3e9:4e2e%wlan0

wlan1 Microsoft Wi-Fi Direct Virtual Adapter

InetAddress: /fe80:0:0:0:f8f6:9c75:d86d:8a22%wlan1

net0 Microsoft 6to4 Adapter

net1 Teredo Tunneling Pseudo-Interface

InetAddress: /2001:0:9d38:6abd:6a:37:3f57:fefa

...

We can also use the following Java 8 technique. A stream and a lambda expression are used to display the IP addresses to generate the same output:

        addresses = element.getInetAddresses();
        Collections
                .list(addresses)
                .stream()
                .forEach((inetAddress) -> {
                    System.out.printf("    InetAddress: %s\n", 
                        inetAddress);
                });

There are numerous InetworkAddress methods, which reveal more details about the network connection. They will be discussed as we encounter them.

Getting a MAC address

A Media Access Control (MAC) address is used to identify an NIC. MAC addresses are usually assigned by the manufacturer of an NIC and are a part of its hardware. Each NIC on a node must have a unique MAC address. Theoretically, all NICs, regardless of their location, will have a unique MAC address. A MAC address consists of 48 bits that are usually written in groups of six pairs of hexadecimal digits. These groups are separated by either a dash or a colon.

Getting a specific MAC address

Normally, MAC addresses are not needed by the average Java programmer. However, they can be retrieved whenever needed. The following method returns a string containing the IP address and its MAC address for a NetworkInterface instance. The getHardwareAddress method returns an array of bytes holding the number. This array is then displayed as a MAC address. Most of this code-segment logic is devoted to formatting the output, where the tertiary operator determines whether a dash should be displayed:

    public String getMACIdentifier(NetworkInterface network) {
        StringBuilder identifier = new StringBuilder();
        try {
            byte[] macBuffer = network.getHardwareAddress();
            if (macBuffer != null) {
                for (int i = 0; i < macBuffer.length; i++) {
                       identifier.append(
                       String.format("%02X%s",macBuffer[i], 
                       (i < macBuffer.length - 1) ? "-" : ""));
                }
            } else {
                return "---";
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        return identifier.toString();
    }

The method is demonstrated in the following example where we use the localhost:

    InetAddress address = InetAddress.getLocalHost();
    System.out.println("IP address: " + address.getHostAddress());
    NetworkInterface network = 
        NetworkInterface.getByInetAddress(address);
    System.out.println("MAC address: " + 
        getMACIdentifier(network));

The output will vary depending on the computer used. One possible output is as follows:

IP address: 192.168.1.5

MAC address: EC-0E-C4-37-BB-72

Note

The getHardwareAddress method will only allow you to access a localhost MAC address. You cannot use it to access a remote MAC address.

Getting multiple MAC addresses

Not all network interfaces will have MAC addresses. This is demonstrated here, where an enumeration is created using the getNetworkInterfaces method, and then each network interface is displayed:

    Enumeration<NetworkInterface> interfaceEnum = 
        NetworkInterface.getNetworkInterfaces();
    System.out.println("Name    MAC Address");
    for (NetworkInterface element : 
            Collections.list(interfaceEnum)) {
        System.out.printf("%-6s  %s\n",
            element.getName(), getMACIdentifier(element));

One possible output is as follows. The output is truncated to save space:

Name MAC Address

lo ---

eth0 ---

eth1 8C-DC-D4-86-B1-05

wlan0 EC-0E-C4-37-BB-72

wlan1 EC-0E-C4-37-BB-72

net0 ---

net1 00-00-00-00-00-00-00-E0

net2 00-00-00-00-00-00-00-E0

...

Alternatively, we can use the following Java implementation. It converts the enumeration into a stream and then processes each element in the stream:

    interfaceEnum = NetworkInterface.getNetworkInterfaces();
    Collections
            .list(interfaceEnum)
            .stream()
            .forEach((inetAddress) -> {
                System.out.printf("%-6s  %s\n",
                    inetAddress.getName(), 
                    getMACIdentifier(inetAddress));
            });

The power of streams comes when we need to perform additional processing, such as filtering out certain interfaces, or converting the interface into a different data type.

主站蜘蛛池模板: 麻江县| 泾源县| 武强县| 西畴县| 多伦县| 铅山县| 元谋县| 栾城县| 平阴县| 兴宁市| 扶风县| 大同市| 莆田市| 芦山县| 前郭尔| 奈曼旗| 栖霞市| 宁波市| 诸暨市| 东台市| 贵州省| 永福县| 黎平县| 隆回县| 凌海市| 外汇| 昌黎县| 宁蒗| 永寿县| 会同县| 鞍山市| 乡城县| 肥西县| 观塘区| 汶上县| 青神县| 郯城县| 玉门市| 阳高县| 南康市| 天柱县|