Hamza Yerlikaya
Hamza Yerlikaya

Reputation: 49339

Generating all IP addresses in the IPv4 Range

What would be a efficient way to generate all possible IP v4 addresses? other than iterating all bytes in a one giant nested for loop.

Upvotes: 3

Views: 5501

Answers (5)

Kip
Kip

Reputation: 109503

Edit: My previous answer would have gone from 128.0.0.0 to 255.255.255.255 to 0.0.0.0 to 127.255.255.255. Presumably you want to go from 0.0.0.0 to 255.255.255.255, so I've edited my solution to do that.

int i = -1;
do {
  i++;

  int b1 = (i >> 24) & 0xff;
  int b2 = (i >> 16) & 0xff;
  int b3 = (i >>  8) & 0xff;
  int b4 = (i      ) & 0xff;

  //Now the IP is b1.b2.b3.b4

} while(i != -1);

Note: if you're confused how this loop will ever end (i.e. how adding 1 to -1 enough times makes it -1 again), read up on two's complement. Basically, adding one to Integer.MAX_VALUE results in Integer.MIN_VALUE, and does not throw any kind of exception.


Old answer. Still hits all IPs, but probably not in the order you desire:

for(long n = Integer.MIN_VALUE; n <= Integer.MAX_VALUE; n++)
{
  int i = (int)n;

  int b1 = (i >> 24) & 0xff;
  int b2 = (i >> 16) & 0xff;
  int b3 = (i >>  8) & 0xff;
  int b4 = (i      ) & 0xff;

  //Now the IP is b1.b2.b3.b4
}

Please note: If the loop control variable was an int instead of a long, this would be an infinite loop (since all ints are always <= Integer.MAX_VALUE).

Upvotes: 11

Edan Maor
Edan Maor

Reputation: 10052

In terms of "efficiency", I don't think there is a much better way than looping through all possible values.

Do take note of two things: 1. There are a lot of addresses, so it won't be that efficient. 2. Not all IP addresses are valid (and there are plenty of addresses which you probably don't intend to go over).

For an example of what IP addresses are valid, take note that all addresses between 224.0.0.0 and 239.255.255.255 are multicast addresses, all addresses starting with 127.x.x.x are invalid, etc.

Upvotes: 1

Andrew McGregor
Andrew McGregor

Reputation: 34692

Not all IPv4 addresses are valid, depending on what purpose they're intended for. See the section on reserved address blocks and the linked RFCs here: http://en.wikipedia.org/wiki/IPv4

So depending on what you want to do, you might need to check for reserved addresses and leave them out.

Upvotes: 3

Eric J.
Eric J.

Reputation: 150238

You can start with an unsigned int/long (32-bit data type) initialized to zero and keep incrementing until you reach 0xffffffff.

The increment operator is usually slightly more efficient than nested loops.

Use bit masks and bit shift operators to pull out any given byte that you are interested in.

Upvotes: 1

YOU
YOU

Reputation: 123927

All Possible? 0.0.0.0 to 255.255.255.255 which is 0 to 0xFFFFFFFF

Upvotes: 2

Related Questions