javaiprangelan

Java Local IP range detect


I am working on a LAN based software, for which I require to detect the range in which systems in the network lies, using Java. The function is required to be similar to "Detect local IP range" in Netscan, a Windows utility software.


Solution

  • If you are wanting the actual local subnet IP range, rather than a list of alive IP addresses in the local subnet, you can use the following code to get the subnet mask size:

    InetAddress localHost = Inet4Address.getLocalHost();
    NetworkInterface ni = NetworkInterface.getByInetAddress(localHost);
    InterfaceAddress ia = ni.getInterfaceAddresses().get(0);
    short mask = ia.getNetworkPrefixLength();
    

    That will give you a short primitive with a value of 1-32, probably 24. Then you can use

    byte[] b = ia.getAddress().getAddress();
    

    Which will give you a byte[] which you will mask against the subnet mask to give you the local address range in some usable format.


    Alternatively if you want a list of alive hosts on the local subnet, an arp-scan using JPCap is the method I would use.