Created
December 20, 2018 23:04
-
-
Save joewright/a25a95250447c7a7a4591666ed830158 to your computer and use it in GitHub Desktop.
ip address range match
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
console.log('something'); | |
const _ = require('lodash'); | |
const { assert } = require('chai'); | |
const SAMPLE_RULES_BLOCK = [ | |
['103.1.108.1','AU'], | |
['3.254.254.254','US'], | |
['5.10.64.17','CN'], | |
['0.0.0.0-0.12.13.14','FR'], | |
['209.88.2.2-209.88.2.255','AZ'], | |
]; | |
/* | |
* returns a country or 'UNKNOWN' | |
* | |
* ipAddress will be a IPv4 address in dot notation: 'a.b.c.d' | |
* assume all addresses passed are valid. | |
*/ | |
function lookupCountry(ipAddress) { | |
// implement me.... | |
var countryTuple = _.find(SAMPLE_RULES_BLOCK, function(rule) { | |
var staticMatch = rule.indexOf(ipAddress) !== -1; | |
if (staticMatch) { | |
return true; | |
} | |
if (rule[0].indexOf('-') === -1) { | |
return false; | |
} | |
var rangeMatchArr = rule[0].split('-'); | |
var rangeMatchMin = rangeMatchArr[0].split('.').map(toNumber); | |
var rangeMatchMax = rangeMatchArr[1].split('.').map(toNumber); | |
var ipAddressParts = ipAddress.split('.').map(toNumber); | |
var inRange = true; | |
var inRangeSoFar; | |
return checkPosition(0); | |
function checkPosition(i) { | |
if (i > 3) { | |
return false; | |
} | |
var min = rangeMatchMin[i]; | |
var max = rangeMatchMax[i]; | |
if (inRangeSoFar) { | |
min = 0; | |
max = 255; | |
} | |
if (ipAddressParts[i] > min && | |
ipAddressParts[i] < max) { | |
inRangeSoFar = true; | |
return true; | |
} else if (ipAddressParts[i] === min || | |
ipAddressParts[i] === max) { | |
if (i === 2) { | |
return true; | |
} | |
return checkPosition(i + 1); | |
} else { | |
// out of range | |
return false; | |
} | |
} | |
}); | |
if (countryTuple) { | |
return countryTuple[1]; | |
} | |
return 'UNKNOWN'; | |
function toNumber(i) { | |
return parseInt(i); | |
} | |
} | |
function test_lookupCountry() { | |
const cases = { | |
'103.1.108.1' : 'AU', | |
'3.254.254.254' : 'US', | |
'5.10.64.17' : 'CN', | |
'127.0.0.1' : 'UNKNOWN', | |
'0.12.1.255' : 'FR', | |
'209.88.2.123' : 'AZ', | |
} | |
_.toPairs(cases).forEach(function([ip, country]) { | |
assert.equal(lookupCountry(ip), country); | |
}) | |
} | |
test_lookupCountry(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment