Last active
June 14, 2018 15:46
-
-
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.
This file contains 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
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