Skip to content

Instantly share code, notes, and snippets.

@DV8FromTheWorld
Created October 12, 2019 22:48
Show Gist options
  • Save DV8FromTheWorld/4d365c7c575b22c779efa7a13ac2d0b9 to your computer and use it in GitHub Desktop.
Save DV8FromTheWorld/4d365c7c575b22c779efa7a13ac2d0b9 to your computer and use it in GitHub Desktop.
Simple function to determine whether a given ip is within a range of ip addresses.
const ipRegex = /([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/
const getIpDigits = (ip) => {
const digits = ipRegex.exec(ip)
if (!digits) {
return [-1, -1, -1, -1]
}
return ipRegex.exec(ip).splice(1).map(stringDigit => +stringDigit)
}
//Ranges for AlertLogic testing servers
const ranges = [
[ '204.110.218.0', '204.110.219.255' ],
[ '208.71.208.0', '208.71.211.255' ],
[ '185.54.124.0', '185.54.127.255' ]
]
.map(([ start, end ]) => [ getIpDigits(start), getIpDigits(end) ])
const ipIsInKnownRange = ip => {
const ipDigits = getIpDigits(ip)
return ranges.some(([start, end]) => {
return start.every((digit, digitIdx) => ipDigits[digitIdx] >= digit)
&& end.every((digit, digitIdx) => ipDigits[digitIdx] <= digit)
})
}
@DV8FromTheWorld
Copy link
Author

DV8FromTheWorld commented Oct 12, 2019

Example usage:

if (ipIsInKnownRange('192.168.0.1')){
  console.log("yup")
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment