How do I convert raw IP address to String?

This example show you how to convert a raw IP address, an array of byte, returned by InetAddress.getAddress() method call to its string representation.

package org.kodejava.net;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class RawIPToString {
    public static void main(String[] args) {
        byte[] ip = new byte[0];
        try {
            InetAddress address = InetAddress.getLocalHost();
            ip = address.getAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String ipAddress = RawIPToString.getIpAddress(ip);
        System.out.println("IP Address = " + ipAddress);

        try {
            InetAddress address = InetAddress.getByName("google.com");
            ip = address.getAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        ipAddress = RawIPToString.getIpAddress(ip);
        System.out.println("IP Address = " + ipAddress);
    }

    /**
     * Convert raw IP address to string.
     *
     * @param rawBytes raw IP address.
     * @return a string representation of the raw ip address.
     */
    private static String getIpAddress(byte[] rawBytes) {
        int i = 4;
        StringBuilder ipAddress = new StringBuilder();
        for (byte raw : rawBytes) {
            ipAddress.append(raw & 0xFF);
            if (--i > 0) {
                ipAddress.append(".");
            }
        }
        return ipAddress.toString();
    }
}

This example will print something like:

IP Address = 30.30.30.60
IP Address = 142.251.10.113

How do I create port scanner program?

In this example you’ll see how to create a simple port scanner program to check the open ports for the specified host name.

package org.kodejava.net;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

public class PortScanner {
    public static void main(String[] args) throws Exception {
        String host = "localhost";
        InetAddress inetAddress = InetAddress.getByName(host);

        String hostName = inetAddress.getHostName();
        for (int port = 0; port <= 65535; port++) {
            try {
                Socket socket = new Socket(hostName, port);
                String text = hostName + " is listening on port " + port;
                System.out.println(text);
                socket.close();
            } catch (IOException e) {
                // empty catch block
            }
        }
    }
}

The result of the code snippet above are:

localhost is listening on port 21
localhost is listening on port 80
localhost is listening on port 135
localhost is listening on port 445
localhost is listening on port 3000
...
...
localhost is listening on port 63342
localhost is listening on port 63467
localhost is listening on port 64891
localhost is listening on port 64921
localhost is listening on port 65001

How do I get MAC address of a host?

Previously for obtaining a MAC address we need to use a native code as a solution. In JDK 1.6 a new method is added in the java.net.NetworkInterface class, this method is getHardwareAddress().

package org.kodejava.net;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class MacAddress {
    public static void main(String[] args) {
        try {
            // InetAddress address = InetAddress.getLocalHost();
            InetAddress address = InetAddress.getByName("192.168.0.105");

            /*
             * Get NetworkInterface for the current host and then read
             * the hardware address.
             */
            NetworkInterface ni = NetworkInterface.getByInetAddress(address);
            if (ni != null) {
                byte[] mac = ni.getHardwareAddress();
                if (mac != null) {
                    /*
                     * Extract each array of mac address and convert it
                     * to hexadecimal with the following format
                     * 08-00-27-DC-4A-9E.
                     */
                    for (int i = 0; i < mac.length; i++) {
                        System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
                    }
                } else {
                    System.out.println("Address doesn't exist or is not accessible.");
                }
            } else {
                System.out.println("Network Interface for the specified address is not found.");
            }
        } catch (UnknownHostException | SocketException e) {
            e.printStackTrace();
        }
    }
}

How do I ping a host?

Since Java 1.5 (Tiger) the java.net.InetAddress class introduces isReachable() method that can be used to ping or check if the address specified by the InetAddress is reachable.

package org.kodejava.net;

import java.net.InetAddress;

public class PingExample {
    public static void main(String[] args) {
        try {
            InetAddress address = InetAddress.getByName("172.16.2.0");

            // Try to reach the specified address within the timeout
            // period. If during this period the address cannot be
            // reach then the method returns false.
            boolean reachable = address.isReachable(10000);

            System.out.println("Is host reachable? " + reachable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

How do I get a localhost hostname?

package org.kodejava.network;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class HostNameExample {
    public static void main(String[] args) {
        try {
            InetAddress address = InetAddress.getLocalHost();

            System.out.println("Hostname: " + address.getHostName());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

An example of output produce by the code snippet above is:

Hostname: Krakatau