Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add function to generate a range of IP addresses as an array #54

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ ip.cidrSubnet('192.168.1.134/26').contains('192.168.1.190') // true
// ipv4 long conversion
ip.toLong('127.0.0.1'); // 2130706433
ip.fromLong(2130706433); // '127.0.0.1'


// ipv4 range generation
ip.range('192.168.0.1','192.168.0.4); // start IP address, end IP address
// [ '192.168.0.1', '192.168.0.2', '192.168.0.3', '192.168.0.4' ]
```

### License
Expand Down
16 changes: 16 additions & 0 deletions lib/ip.js
Original file line number Diff line number Diff line change
Expand Up @@ -410,3 +410,19 @@ ip.fromLong = function(ipl) {
(ipl >> 8 & 255) + '.' +
(ipl & 255) );
};

ip.range = function(start_ip, end_ip) {
var start_long = ip.toLong(start_ip);
var end_long = ip.toLong(end_ip);
if (start_long > end_long) {
var tmp = start_long;
start_long = end_long;
end_long = tmp;
}
var range_array = [];
var i;
for (i = start_long; i <= end_long; i++) {
range_array.push(ip.fromLong(i));
}
return range_array;
};
11 changes: 11 additions & 0 deletions test/api-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -399,4 +399,15 @@ describe('IP library for node.js', function() {
assert.equal(ip.fromLong(4294967295), '255.255.255.255');
});
})

describe('range() method', function() {
it('should repond with array of ipv4 addresses', function() {
var range_array = ip.range('192.168.0.0', '192.168.1.255');
assert.equal(range_array.length, 512);
assert.equal(range_array[0], '192.168.0.0');
assert.equal(range_array[1], '192.168.0.1');
assert.equal(range_array[510], '192.168.1.254');
assert.equal(range_array[511], '192.168.1.255');
});
})
});