diff --git a/lib/ip.js b/lib/ip.js index c1799a8..ab010bd 100644 --- a/lib/ip.js +++ b/lib/ip.js @@ -400,6 +400,9 @@ ip.address = function(name, family) { }; ip.toLong = function(ip) { + if (!this.isV4Format(ip)) { + throw new Error('.toLong requires valid IPv4 as input: ' + ip); + } var ipl = 0; ip.split('.').forEach(function(octet) { ipl <<= 8; diff --git a/test/api-test.js b/test/api-test.js index 2e390f9..b39fcfa 100644 --- a/test/api-test.js +++ b/test/api-test.js @@ -386,7 +386,7 @@ describe('IP library for node.js', function() { var addr = ip.address(nic, 'ipv6'); assert.ok(!addr || net.isIPv6(addr)); }); - }) + }); }); }); }); @@ -396,6 +396,17 @@ describe('IP library for node.js', function() { assert.equal(ip.toLong('127.0.0.1'), 2130706433); assert.equal(ip.toLong('255.255.255.255'), 4294967295); }); + it('should be able handle bad input', function() { + assert.throws(function () { + ip.toLong('fd12:3456:789a:1::1'); + }, Error); + assert.throws(function () { + ip.toLong(null); + }, Error); + assert.throws(function () { + ip.toLong(undefined); + }, Error); + }); }); describe('fromLong() method', function() {