Neel
Neel

Reputation: 21297

Create ip range from start and end point in javascript or jquery

I have start IP address and end IP address. I want to create range between these ip address.

For example :

start = '10.10.1.0'
end = '10.10.10.10'

Output must be like.

10.10.1.0
10.10.1.1
10.10.1.2
...
...
10.10.1.255
10.10.2.0
10.10.2.1
...
...
10.10.10.9
10.10.10.10

Is there any object in JavaScript which give range from start and end IP address?

Upvotes: 1

Views: 2869

Answers (2)

benathon
benathon

Reputation: 7633

Looking at IP addresses in hex is really useful here. Each number between the periods is called two "octet" which means grouping of 16 bits. The maximum value of each number is 255, or 0xFF in hex. Your starting address of 10.10.1.0 is represented as 0x0A0A0100 in hex. Your ending address is 0x0A0A0A0A.

I've written a JSFiddle to show you how simple it is to count through IP addresses once you represent them in hex.

http://jsfiddle.net/sL7VM/

Here is the most important part of the code:

for(var i = 0x0A0A0100; i < 0x0A0A0A0A; i++)
{   
    var oc4 = (i>>24) & 0xff;
    var oc3 = (i>>16) & 0xff;
    var oc2 = (i>>8) & 0xff;
    var oc1 = i & 0xff;

    $('#output').append(oc4 + "." + oc3 + "." + oc2 + "." + oc1 + "<br>");
}

Upvotes: 4

FamiliarPie
FamiliarPie

Reputation: 606

There is no way to do this in native javascript other than splitting the start and end on the "." char and then creating a loop. It may be achievable by a library.

Have you had a look at this one? https://code.google.com/p/iplib-js/

Upvotes: 2

Related Questions