diff --git a/lib/ip.js b/lib/ip.js index c1799a8..d827546 100644 --- a/lib/ip.js +++ b/lib/ip.js @@ -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('/'); diff --git a/test/api-test.js b/test/api-test.js index 2e390f9..3bb5369 100644 --- a/test/api-test.js +++ b/test/api-test.js @@ -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');