Skip to content
Open
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
34 changes: 34 additions & 0 deletions lib/ip.js
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,40 @@ ip.subnet = function(addr, mask) {
};
};

ip.range = function(addr) {
var from = false;
var to = false;

var m = addr.match(/((?:[0-9]{1,3}\.){3})([0-9]{1,3})-([0-9]{1,3})/);
if (m) {
from = m[1] + m[2];
to = m[1] + m[3];
}

m = addr
.match(/((?:[0-9]{1,3}\.){3}[0-9]{1,3})-((?:[0-9]{1,3}\.){3}[0-9]{1,3})/);
if (m) {
from = m[1];
to = m[2];
}

if (!from || !to) {
return false;
}

var fromLong = ip.toLong(from);
var toLong = ip.toLong(to);

return {
firstAddress: from,
lastAddress: to,
length: toLong - fromLong,
contains: function(other) {
return ip.toLong(other) >= fromLong && ip.toLong(other) <= toLong;
}
};
};

ip.cidrSubnet = function(cidrString) {
var cidrParts = cidrString.split('/');

Expand Down
45 changes: 45 additions & 0 deletions test/api-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,51 @@ describe('IP library for node.js', function() {
});
});

describe('range() method', function() {
var ipv4RangeShort = ip.range('192.168.0.100-249');
var ipv4RangeLong = ip.range('192.168.0.100-192.168.1.100');

it('should compute an ipv4 range\'s first address', function() {
assert.equal(ipv4RangeShort.firstAddress, '192.168.0.100');
});

it('should compute an ipv4 range\'s last address', function() {
assert.equal(ipv4RangeShort.lastAddress, '192.168.0.249');
});

it('should compute an ipv4 range number of addresses', function() {
assert.equal(ipv4RangeShort.length, 149);
});

it('should know whether a subnet contains an address', function() {
assert.equal(ipv4RangeShort.contains('192.168.0.180'), true);
});

it('should know whether a subnet contains an address', function() {
assert.equal(ipv4RangeShort.contains('192.168.0.255'), false);
});

it('should compute an ipv4 range\'s first address', function() {
assert.equal(ipv4RangeLong.firstAddress, '192.168.0.100');
});

it('should compute an ipv4 range\'s last address', function() {
assert.equal(ipv4RangeLong.lastAddress, '192.168.1.100');
});

it('should compute an ipv4 range number of addresses', function() {
assert.equal(ipv4RangeLong.length, 256);
});

it('should know whether a subnet contains an address', function() {
assert.equal(ipv4RangeLong.contains('192.168.0.180'), true);
});

it('should know whether a subnet contains an address', function() {
assert.equal(ipv4RangeLong.contains('192.168.1.255'), false);
});
});

describe('cidrSubnet() method', function() {
// Test cases calculated with http://www.subnet-calculator.com/
var ipv4Subnet = ip.cidrSubnet('192.168.1.134/26');
Expand Down