Let us see how we could build a simple network scanner using Java to just see if there are any up and running hosts connected to the network we are connected to. Basically what you need is the java.net for the network stuff and the java.util or the java.io package for IO management.

First lets import the packages. We will only need the InetAddress class from the java.net package:

import java.net.InetAddress;
import java.util.*;

Next we move on to the main code. Within the main method, we first setup the IO objects and prompt the user for input. Here we will be expecting the user to provide us the subnet of the network they are connected to:

Scanner input = new Scanner(System.in);
System.out.println("Enter subnet:");
String subnet = input.nextLine();

Now, we are ready to scan the network. For we have to scan all the possible hosts, we use a for loop running 1 through 255 and each time a host is selected as .1, .2, .3, … 255 format. Then we use the InetAddress class which represents a specific IP address, to check whether the selected host is reachable.

Complete code

import java.net.InetAddress;
import java.util.*;

public class NetScanner {
    public static void main(String[] args) throws Exception {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter subnet:");
        String subnet = input.nextLine();

        for (int i = 0; i < 255; i++) {
            int timeout = 10;
            String host = subnet + "." + i;
            if (InetAddress.getByName(host).isReachable(timeout)) {
                System.out.println(host + " is reachable");
            }
        }
    }
}