Last active
March 3, 2021 14:46
-
-
Save albrow/5709119 to your computer and use it in GitHub Desktop.
A short javascript function to convert an IP address in dotted decimal notation to a regular decimal. This is useful for IP address geolocation lookups. Supports both IPv4 and IPv6 addresses. http://en.wikipedia.org/wiki/Ip_address
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
// convert the ip address to a decimal | |
// assumes dotted decimal format for input | |
function convertIpToDecimal(ip) { | |
// a not-perfect regex for checking a valid ip address | |
// It checks for (1) 4 numbers between 0 and 3 digits each separated by dots (IPv4) | |
// or (2) 6 numbers between 0 and 3 digits each separated by dots (IPv6) | |
var ipAddressRegEx = /^(\d{0,3}\.){3}.(\d{0,3})$|^(\d{0,3}\.){5}.(\d{0,3})$/; | |
var valid = ipAddressRegEx.test(ip); | |
if (!valid) { | |
return false; | |
} | |
var dots = ip.split('.'); | |
// make sure each value is between 0 and 255 | |
for (var i = 0; i < dots.length; i++) { | |
var dot = dots[i]; | |
if (dot > 255 || dot < 0) { | |
return false; | |
} | |
} | |
if (dots.length == 4) { | |
// IPv4 | |
return ((((((+dots[0])*256)+(+dots[1]))*256)+(+dots[2]))*256)+(+dots[3]); | |
} else if (dots.length == 6) { | |
// IPv6 | |
return ((((((((+dots[0])*256)+(+dots[1]))*256)+(+dots[2]))*256)+(+dots[3])*256)+(+dots[4])*256)+(+dots[5]); | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your regular expression fails for IPv6 addresses.