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.example.net;

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

public class RawIPToString {
    public static void main(String[] args) {
        InetAddress address = null;

        byte[] ip = new byte[0];
        try {
            address = InetAddress.getLocalHost();
            ip = address.getAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        String ipAddress = RawIPToString.getIpAddress(ip);
        System.out.println("IP Address = " + ipAddress);

        try {
            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.
     */
    public static String getIpAddress(byte[] rawBytes) {
        int i = 4;
        String ipAddress = "";
        for (byte raw : rawBytes)
        {
            ipAddress += (raw & 0xFF);
            if (--i > 0)
            {
                ipAddress += ".";
            }
        }

        return ipAddress;
    }
}

This example will print:

IP Address = 182.0.135.67
IP Address = 209.85.132.104

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.example.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) {
                String s = hostName + " is not listening on port " + port;
                System.out.println(s);
            }
        }
    }
}