Skip to content

Instantly share code, notes, and snippets.

@albrow
Last active Mar 3, 2021
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@aherriot aherriot commented Apr 25, 2016

Your regular expression fails for IPv6 addresses.

@dkddk

This comment has been minimized.

Copy link

@dkddk 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