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 create a client-server socket communication?

In this example you’ll see how to create a client-server socket communication. The example below consist of two main classes, the ServerSocketExample and the ClientSocketExample. The server application listen to port 7777 at the localhost. When we send a message from the client application the server receive the message and send a reply to the client application.

The communication in this example using the TCP socket, it means that there is a fixed connection line between the client application and the server application.

package org.kodejava.net;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.lang.Runnable;
import java.lang.Thread;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerSocketExample {
    private static final int PORT = 7777;
    private ServerSocket server;

    private ServerSocketExample() {
        try {
            server = new ServerSocket(PORT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ServerSocketExample example = new ServerSocketExample();
        example.handleConnection();
    }

    private void handleConnection() {
        System.out.println("Waiting for client message...");

        // The server do a loop here to accept all connection initiated by the
        // client application.
        while (true) {
            try {
                Socket socket = server.accept();
                new ConnectionHandler(socket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

class ConnectionHandler implements Runnable {
    private final Socket socket;

    ConnectionHandler(Socket socket) {
        this.socket = socket;

        Thread t = new Thread(this);
        t.start();
    }

    public void run() {
        try {
            // Read a message sent by client application
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            String message = (String) ois.readObject();
            System.out.println("Message Received: " + message);

            // Send a response information to the client application
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject("Hi...");

            ois.close();
            oos.close();
            socket.close();

            System.out.println("Waiting for client message...");
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
package org.kodejava.net;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.InetAddress;
import java.net.Socket;

public class ClientSocketExample {
    public static void main(String[] args) {
        try {
            // Create a connection to the server socket on the server application
            InetAddress host = InetAddress.getLocalHost();
            Socket socket = new Socket(host.getHostName(), 7777);

            // Send a message to the client application
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject("Hello There...");

            // Read and display the response message sent by server application
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            String message = (String) ois.readObject();
            System.out.println("Message: " + message);

            ois.close();
            oos.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

To test the application you need to start the server application. Each time you run the client application it will send a message “Hello There…” and in turns the server reply with a message “Hi…”.

How do I get response header from HTTP request?

package org.kodejava.net;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HttpResponseHeaderDemo {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://kodejava.org/index.php");
            URLConnection connection = url.openConnection();

            Map<String, List<String>> responseMap = connection.getHeaderFields();
            for (String key : responseMap.keySet()) {
                System.out.print(key + " = ");

                List<String> values = responseMap.get(key);
                for (String value : values) {
                    System.out.print(value + ", ");
                }
                System.out.println();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The result produced by the code above are:

null = HTTP/1.1 200 OK, 
Referrer-Policy = no-referrer-when-downgrade, 
Content-Length = 147566, 
Content-Type = text/html; charset=UTF-8, 
Connection = keep-alive, 
Date = Sun, 26 Sep 2021 03:59:06 GMT, 
Accept-Ranges = bytes, 
Vary = Accept-Encoding, Accept-Encoding, 
Link = <https://wp.me/8avgG>; rel=shortlink, <https://kodejava.org/wp-json/>; rel="https://api.w.org/",  

How do I create a URL object?

package org.kodejava.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class URLDemo {
    public static void main(String[] args) {
        try {
            // Creating a url object by specifying each parameter separately, including
            // the protocol, hostname, port number, and the page name
            URL url = new URL("https", "kodejava.org", 443, "/index.php");

            // We can also specify the address in a single line
            url = new URL("https://kodejava.org:443/index.php");

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I read or download web page content?

You want to create a program that read a webpage content of a website page. The example below use the URL class to create a connection to the website. You create a new URL object and pass the URL information of a page. After the object created you can open a stream connection using the openStream() method of the URL object.

Next, you can read the stream using the BufferedReader object. This reader allows you to read line by line from the stream. To write it to a file create a writer using the BufferedWriter object and specify the file name where the downloaded page will be stored.

When all the content are read from the stream and stored in a file close the BufferedReader object and the BufferedWriter object at the end of your program.

package org.kodejava.net;

import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class UrlReadPageDemo {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://kodejava.org");

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));
            BufferedWriter writer = new BufferedWriter(
                    new FileWriter("data.html", StandardCharsets.UTF_8));

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                writer.write(line);
                writer.newLine();
            }

            reader.close();
            writer.close();
        } catch (IOException 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

How do I get IP address of localhost?

The example here show you how to get an IP or host address using the java.net.InetAddress class. To get an instance of InetAddress we call a static method of this class, the method is getLocalHost(), which return the local host address. Next, to get the IP address we can call the getHostAddress() method.

package org.kodejava.net;

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

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

            System.out.println("IP Address = " + ip);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

The result of this code snippet:

IP Address = 30.30.30.60