Saturday, February 6, 2016

Java code to listing Network Interface Addresses, run on Raspberry Pi/Raspbian Jessie


The following example program lists all the network interfaces and their addresses on a machine, run on Raspberry Pi 2/Raspbian Jessie.


JavaListInetAddress.java
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;

public class JavaListInetAddress {

    public static void main(String[] args) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }
    
    static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        System.out.printf("Display name: %s\n", netint.getDisplayName());
        System.out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
        for (InetAddress inetAddress : Collections.list(inetAddresses)) {
            System.out.printf("InetAddress: %s\n", inetAddress);
        }
        System.out.printf("\n");
     }
    
}


reference: https://docs.oracle.com/javase/tutorial/networking/nifs/listing.html

Related:
Java code to listing Network Interface Addresses, run on Windows 10
Python code to find my IP address, run on Raspberry Pi/Raspbian Jessie
C example to getting IP address from a network interface, run on Raspberry Pi/Raspbian Jessie

Next:
Java to list Network Interface Parameters (include MAC address)

No comments: