Network Information
Use the getNetworkInterfaces method to obtain information abut all network ports on the current host.
import Java.net.Inet4Address;
import Java.net.InetAddress;
import Java.net.NetworkInterface;
import Java.util.Enumeration;
public class NetworkInterfaceTest {
public static void main(String[] args) throws Exception {
//Obtains information about all network ports of the local host.
Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
while (nifs.hasMoreElements()) {
NetworkInterface nif = nifs.nextElement();
// Obtains the IP address bound to the network port. Generally, there is only one IP address bound to the network port.
Enumeration<InetAddress> addresses = nif.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
if (addr instanceof Inet4Address) {// Only IPv4 address.
System.out.println("NIC port name: "+ nif.getName());
System.out.println("NIC port address: "+ addr.getHostAddress());
System.out.println();
}
}
}
}
}
Execution result on the Kunpeng platform:
[root@centos7 test]# Java NetworkInterfaceTest NIC port name: br-4932c6ca6ce6 NIC port address: 192.168.48.1 NIC port name: docker0 NIC port address: 172.17.0.1 NIC port name: eth1 NIC port address: 122.0.0.154 NIC port name: eth0 NIC port address: 11.0.0.154 NIC port name: lo NIC port address: 127.0.0.1
Parent topic: Java