Skip to content

Instantly share code, notes, and snippets.

@livingston
Created January 12, 2010 14:22
Show Gist options
  • Save livingston/275231 to your computer and use it in GitHub Desktop.
Save livingston/275231 to your computer and use it in GitHub Desktop.
converts IP address to decimal format
/* IP2Decimal.js - converts IP address to decimal format
* @author - Livingston Samuel
*/
var IP2Decimal = function (ip) {
var ipSyntax = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/, ipArr, i = 4, decVal = 0;
if (ipSyntax.test(ip)) {
ipArr = ip.split(".");
while (i--) {
if (ipArr[i] > 255) {
throw new Error("Invalid IP Address");
} else {
decVal += Math.pow(2, (8 * i)) * ipArr[3 - i];
}
}
return decVal;
} else {
throw new Error("Invalid IP Address");
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment