Skip to content

Instantly share code, notes, and snippets.

@albrow
Last active March 3, 2021 14:46
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save albrow/5709119 to your computer and use it in GitHub Desktop.
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
// 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;
}
@aherriot
Copy link

Your regular expression fails for IPv6 addresses.

@dkddk
Copy link

dkddk commented Jan 9, 2020

104.244.42.1

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