Access the network interface in Java

TL;DR

I've never done it.

environment

On Ubuntu Linux 18.04 LTS

$ uname -srvmpio
Linux 4.18.0-25-generic #26~18.04.1-Ubuntu SMP Thu Jun 27 07:28:31 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux


$ lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 18.04.4 LTS
Release:	18.04
Codename:	bionic

Java 11。

$ java --version
openjdk 11.0.6 2020-01-14
OpenJDK Runtime Environment (build 11.0.6+10-post-Ubuntu-1ubuntu118.04.1)
OpenJDK 64-Bit Server VM (build 11.0.6+10-post-Ubuntu-1ubuntu118.04.1, mixed mode, sharing)

java.net.NetworkInterface

Use java.net.NetworkInterface to access the network interface.

java.net.NetworkInterface

Information on the host's network interface.

$ ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
    inet 192.168.200.130/24 brd 192.168.200.255 scope global dynamic noprefixroute ens33
       valid_lft 1737sec preferred_lft 1737sec
    inet6 fe80::6f10:63fc:a80e:7ea0/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
3: br-72f78aadc23c: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default 
    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
    inet 172.19.0.1/16 brd 172.19.255.255 scope global br-72f78aadc23c
       valid_lft forever preferred_lft forever
4: br-8dd168bc4c0e: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default 
    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
    inet 172.18.0.1/16 brd 172.18.255.255 scope global br-8dd168bc4c0e
       valid_lft forever preferred_lft forever
5: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default 
    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
    inet 172.22.0.1/16 brd 172.22.255.255 scope global docker0
       valid_lft forever preferred_lft forever

Sample code. You can get all network interfaces with NetworkInterface.getNetworkInterfaces (), and you can get network interfaces with network interface name, index, and ʻInetAddress`.

App.java

import java.io.IOException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.List;
import java.util.StringJoiner;

public class App {
    public static void main(String... args) throws SocketException {
        List<NetworkInterface> networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces());

        networkInterfaces.forEach(ni -> {
            try {
                System.out.printf(
                        "name = %s, addresses = %s, mac address = %s%n",
                        ni.getName(),
                        Collections.list(ni.getInetAddresses()),
                        formatBinaryToHexString(ni.getHardwareAddress())
                );
            } catch (IOException e) {
                // ignore
            }
        });

        NetworkInterface ni = NetworkInterface.getByName("ens33");
        System.out.printf(
                "name = %s, addresses = %s, mac address = %s%n",
                ni.getName(),
                Collections.list(ni.getInetAddresses()),
                formatBinaryToHexString(ni.getHardwareAddress())
        );
    }

    static String formatBinaryToHexString(byte[] binary) {
        if (binary == null) {
            return "[]";
        }

        StringJoiner joiner = new StringJoiner(":");

        for (byte b : binary) {
            joiner.add(String.format("%02x", b));
        }

        return joiner.toString();
    }
}

Execution example.

name = docker0, addresses = [/172.22.0.1], mac address = xx:xx:xx:xx:xx:xx
name = br-8dd168bc4c0e, addresses = [/172.18.0.1], mac address = xx:xx:xx:xx:xx:xx
name = br-72f78aadc23c, addresses = [/172.19.0.1], mac address = xx:xx:xx:xx:xx:xx
name = ens33, addresses = [/fe80:0:0:0:6f10:63fc:a80e:7ea0%ens33, /192.168.200.130], mac address = xx:xx:xx:xx:xx:xx
name = lo, addresses = [/0:0:0:0:0:0:0:1%lo, /127.0.0.1], mac address = []
name = ens33, addresses = [/fe80:0:0:0:6f10:63fc:a80e:7ea0%ens33, /192.168.200.130], mac address = xx:xx:xx:xx:xx:xx

Recommended Posts

Access the network interface in Java
Callable Interface in Java
Guess the character code in Java
Specify the java location in eclipse.ini
java (interface)
Unzip the zip file in Java
[java] interface
Parsing the COTOHA API in Java
Call the super method in Java
Get the result of POST in Java
Java reference to understand in the figure
Try using the Stream API in Java
Understand java interface in your own way
Call the Windows Notification API in Java
I tried the new era in Java
[Java] Use cryptography in the standard library
Organized memo in the head (Java --Array)
Try calling the CORBA service in Java 11+
What is the main method in Java?
How to get the date in java
The story of writing Java in Emacs
Console input in Java (understanding the mechanism)
About Java interface
Partization in Java
Changes in Java 11
Rock-paper-scissors in Java
Run x11 apps in a Docker container (supports network access from the container)
[Java] About interface
[Java] Functional interface
About interface, java interface
Pi in Java
FizzBuzz in Java
Regarding the transient modifier and serialization in Java
The story of low-level string comparison in Java
[Java] Handling of JavaBeans in the method chain
About the confusion seen in startup Java servers
The story of making ordinary Othello in Java
About the idea of anonymous classes in Java
ChatWork4j for using the ChatWork API in Java
A story about the JDK in the Java 11 era
Organized memo in the head (Java --Control syntax)
The intersection type introduced in Java 10 is amazing (?)
[Java] Access the signed URL of s3 (signed version 2)
The story of learning Java in the first programming
Measure the size of a folder in Java
Feel the passage of time even in Java
Organized memo in the head (Java --instance edition)
[Java] Read the file in src / main / resources
Organized memo in the head (Java --Data type)
[Deep Learning from scratch] in Java 3. Neural network
Display "Hello World" in the browser using Java
[Java] Judgment by entering characters in the terminal
Display "Hello World" in the browser using Java
Try using the COTOHA API parsing in Java
[Java] Something is displayed as "-0.0" in the output
Import files of the same hierarchy in Java
I didn't know that inner classes could be defined in the [Java] interface
Get the URL of the HTTP redirect destination in Java
[java] sort in list
[Java] Let's declare variables used in the loop in the loop [Variables in the block]
Read JSON in Java