Friday, April 1, 2011

Working with in JDK6

JDK6 has a neat little class that lets you get information about all of your network interfaces. We'll look at some code that print out most of the available information, including deciding the hardware or MAC address. If comes to us as a byte[] of length. We also encounter an ip address encoded as a byte[] that we'll decode.

try {
    Enumeration<NetworkInterface> ns = NetworkInterface.getNetworkInterfaces();
    while (ns.hasMoreElements()) {           
        NetworkInterface n = ns.nextElement();
        System.out.println("** Ethernet Name=" + n.getName());
        System.out.println("** Ethernet DisplayName=" + n.getDisplayName());
        byte[] b = n.getHardwareAddress();
        System.out.println("** Ethernet HardwareAddress=" + formatHardwareAddress(b));
        Enumeration<InetAddress> p = n.getInetAddresses();
        while (p.hasMoreElements()) {
            InetAddress ia = p.nextElement();
            System.out.println("**** Address CanonicalHostName=" + ia.getCanonicalHostName());
            System.out.println("**** Address HostAddress=" + ia.getHostAddress());
            System.out.println("**** Address HostName=" + ia.getHostName());
            System.out.println("**** Address Raw=" + formatRawIpAddress(ia.getAddress()));
        for (InterfaceAddress ia: n.getInterfaceAddresses()) {
            System.out.println("**** Interface Address=" + ia.getAddress());
            System.out.println("**** Interface Broadcast=" + ia.getBroadcast());
            System.out.println("**** Interface NetworkPrefixLength=" + ia.getNetworkPrefixLength());
} catch (SocketException ex) {
    Logger.getLogger(UuidService.class.getName()).log(Level.SEVERE, null, ex);

First, we'll get a list of available NetworkInterfaces. We'll then iterate through and print out that information. Normally you'll see your external interface along with localhost.

We need 2 more methods to round out this example. We need to be able to decode both the hardware address and the byte[] encoded ip address.

private String formatHardwareAddress(byte[] hardwareAddress) {
    if (hardwareAddress == null) { return ""; }
    StringBuilder sb = new StringBuilder();
    for (int i=0; i<hardwareAddress.length -1; i++) {
        sb.append(Integer.toString(hardwareAddress[i] & 0xff, 16).toUpperCase()).append(":");
    sb.append(Integer.toString(hardwareAddress[hardwareAddress.length-1] & 0xff, 16).toUpperCase());
    return (sb.toString());

private String formatRawIpAddress(byte[] rawAddress) {
    if (rawAddress == null) { return ""; }
    StringBuilder sb = new StringBuilder();
    for (int i=0; i<rawAddress.length -1; i++) {
    return (sb.toString());

There you have it. Run the code and see what you get on your own machine.