2

I am new to java and am doing a project using Java.

I have an IP( for ex: 192.168.0.10) and a subnet mask (let us say, 255.255.255.0). I need a list of all the ip addresses in this sub-net. What I can think of best is the naive solution(in which I have to deal with bits and all). Does anyone know a better/e.legant way of doing this.

If we consider the example we will have list of ip's as 192.168.0.1. 192.168.0.2, 192.168.0.3, ..... , 192.168.0.254

Any help appreciated.

[Edit] Naive approach I have thought of:

Construct a integer by considering the ip address you have and the subnet. In our case it would be this in binary representation 11000000.10101000.00000000.00000000 (dots are added for readability). Increment this number by 1 till the 24 bits from left toggles. The first tile it toggles we have generated all numbers which can be possible ip in this subnet. Now the task is to generate ip from a 32 bit number which can be done by writing a function which extracts 8 bits at a time.

Aman Deep Gautam
  • 8,091
  • 21
  • 74
  • 130

2 Answers2

3

There is Apache Commons SubnetUtils

SubnetUtils utils = new SubnetUtils("192.168.0.10", "255.255.255.0");
String[] addresses = utils.getInfo().getAllAddresses();

getHighAddress and getLowAddress might be very useful to you. See more details in docs.

Nikolay Kuznetsov
  • 9,467
  • 12
  • 55
  • 101
1

How about this?

UPDATE: Small tweak to prevent enumerating the two special purpose IPs (Network IP and Broadcast IP). I think this is the simplest solution without extra dependencies.

FINAL UPDATE: I made a correction to account for Java's rules in rounding signed division.

public class ListIPs
{
    static int IPNum(int a, int b, int c, int d)
    {
        int ip = ((a * 256 | b) * 256 | c) * 256 | d;
        return ip;
    }

    static void ListIPs(int ip, int mask)
    {
        int index;
        int count = 1;
        int temp = mask;
        long a, b, c, d;

        while ((temp & 1) == 0)
        {
            count *= 2;
            temp >>= 1;
        }

        for (index = 1; index < count -1; index++)
        {
            long newIP = ((ip & mask) | index) & 0xFFFFFFFFL;


            d = newIP & 0xFF;
            c = (newIP / 256) & 0xFF;
            b = (newIP / 65536) & 0xFF;
            a = (newIP / 16777216) & 0xFF;

            System.out.println("" + a + "." + b + "." + c + "." + d);
        }
    }

    public static void main(String[] args)
    {
        ListIPs(IPNum(192, 168, 0, 10), IPNum(255, 255, 255, 0));
    }
}
Kevin A. Naudé
  • 3,992
  • 19
  • 20