Skip to content

Instantly share code, notes, and snippets.

@showrav017
Last active December 15, 2016 12:47
Show Gist options
  • Save showrav017/fbcdb894d000663d402db52ff92a10e3 to your computer and use it in GitHub Desktop.
Save showrav017/fbcdb894d000663d402db52ff92a10e3 to your computer and use it in GitHub Desktop.
Generate IP Address from a range
/**
* Developed by Muhammad Ehsanul Hoque on December 15, 2016
* Took helop form the link StackOverflow
* http://stackoverflow.com/questions/22927298/create-ip-range-from-start-and-end-point-in-javascript-or-jquery
*
* Credit goes to portforwardpodcast(http://stackoverflow.com/users/836450/portforwardpodcast) for the loop code.
*
* Just call IPAddressGenerator.Generate("XXX.XXX.XXX.XXX", "XXX.XXX.XXX.XXX") and in return you will get range of ip as array.
*
* IPAddressGenerator.Generate(start_ip, end_ip, stop_at)
*
* start_ip : String, Mandatory, Range Start IP
* end_ip : String, Mandatory, Range End IP
* stop_at: Integer, Optional, When the ip generation loop will break.
*
* By default the script will stop after generate 1000 ip's. But you can control it using stop_at parameter.
*
* Thanks
*/
var IPAddressGenerator =
{
IPAddresses:[],
Generate:function(start_ip, end_ip, stop_at)
{
if (start_ip === undefined) {
return [];
}
if (end_ip === undefined) {
return [];
}
if (stop_at === undefined || isNaN(stop_at)) {
stop_at = 1000;
}
start_ip = start_ip.split(".");
end_ip = end_ip.split(".");
var pointer = 0;
var start_ip_hex = ("0x")+IPAddressGenerator.PrepareHexDigit(start_ip[0])+IPAddressGenerator.PrepareHexDigit(start_ip[1])+IPAddressGenerator.PrepareHexDigit(start_ip[2])+IPAddressGenerator.PrepareHexDigit(start_ip[3])
var end_ip_hex = ("0x")+IPAddressGenerator.PrepareHexDigit(end_ip[0])+IPAddressGenerator.PrepareHexDigit(end_ip[1])+IPAddressGenerator.PrepareHexDigit(end_ip[2])+IPAddressGenerator.PrepareHexDigit(end_ip[3])
for(var i = start_ip_hex; i <= end_ip_hex; i++)
{
var oc4 = (i>>24) & 0xff;
var oc3 = (i>>16) & 0xff;
var oc2 = (i>>8) & 0xff;
var oc1 = i & 0xff;
IPAddressGenerator.IPAddresses.push(oc4 + "." + oc3 + "." + oc2 + "." + oc1);
pointer=pointer+1
if(stop_at !==0 && stop_at==pointer)
{
break;
}
}
return IPAddressGenerator.IPAddresses;
},
PrepareHexDigit:function(digit)
{
var HEX_digit = parseInt(digit).toString(16).toUpperCase()
if(HEX_digit.length<2)
{
return "0"+HEX_digit
}
else
{
return HEX_digit
}
}
}
// For Example
console.log(IPAddressGenerator.Generate("1.1.1.1", "1.1.1.100"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment