Skip to content

Instantly share code, notes, and snippets.

@dsantuc
Last active June 14, 2018 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsantuc/3bf7fc3305120fb87b171d7bd3374485 to your computer and use it in GitHub Desktop.
Save dsantuc/3bf7fc3305120fb87b171d7bd3374485 to your computer and use it in GitHub Desktop.
JavaScript to convert IPv4 addresses from dotted-decimal notation to integers and back.
function ip2int (ip) {
var ipVal = 0;
ip.split(".").forEach(function (octet, i, arr) {
var exp = 8 * (arr.length - i - 1);
ipVal += octet * Math.pow(2, exp);
});
return ipVal;
}
function int2ip (n) {
var octets = [];
var len = 2;
var hexString = n.toString(16);
if (hexString.length % 2) {
hexString = "0" + hexString;
}
for (var i=0; i<= hexString.length-len; i+=len) {
octets.push(parseInt(hexString.substr(i, len), 16));
}
return octets.join(".");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment