Last active
March 30, 2016 19:09
-
-
Save ajmas/dc0b5507b3a8e7995c87e2c23358c9e4 to your computer and use it in GitHub Desktop.
Some IPv6 utility functions I put together, improvements appreciated
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
var ipv4Regex = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/; | |
function expandIPv6(ipv6ColonNotation) { | |
var pad = "0000" | |
var count = (ipv6ColonNotation.match(/:/g)|| []).length; | |
if (count == 0 || count > 7) { | |
// too few or too many colons | |
return "err"; | |
} | |
var blocks = ipv6ColonNotation.split(':'); | |
var emptyBlock = 0; | |
for (i=0; i<blocks.length; i++) { | |
if (blocks[i].length < 4 & blocks[i].length > 0) { | |
blocks[i] = pad.substring(0, pad.length - blocks[i].length) + blocks[i]; | |
console.log(blocks[i]); | |
} else if (blocks[i].length === 0 && emptyBlock === 0 ) { | |
for (j=0; j <(7-count); j++) { | |
blocks.splice(i, 0, pad); | |
} | |
emptyBlock = 1; | |
} else if (blocks[i].length === 0 && emptyBlock === 1 ) { | |
blocks[i] = pad; | |
} | |
} | |
var str = ''; | |
for (i=0; i<7; i++) { | |
str += blocks[i] + ':'; | |
} | |
str += blocks[7] | |
return str; | |
} | |
function ipv4toIPv6(address) { | |
var ipv6Str = "0000:0000:0000:0000:0000:ffff:" | |
parts = ipv4Regex.exec(address); | |
parts.shift(); | |
for (i=0; i<parts.length; i++) { | |
ipv6Str += parseInt(parts[i]).toString(16); | |
if (i === 2) { | |
ipv6Str += ':'; | |
} | |
} | |
return ipv6Str; | |
} | |
// not all IPv6 addresses are convertable | |
function ipv6ToIPv4(address) { | |
var prefix = "0000:0000:0000:0000:0000:ffff:" | |
var ipv4Addr = ''; | |
address = expandIPv6(address); | |
if (!address.startsWith(prefix)) { | |
return; | |
} | |
address = address.replace(/:/g,''); | |
for (i=0; i<4; i++) { | |
ipv4Addr += parseInt(address.substring(24 + (i*2), 24 + (i*2) + 2),16) | |
if (i<3) { | |
ipv4Addr += '.'; | |
} | |
} | |
return ipv4Addr; | |
} | |
function ipv6toBinary(address) { | |
var binAddr = 0; | |
if (address.indexOf('.') > 0) { | |
address = ipv4toIPv6(address); | |
} | |
address = expandIPv6(address); | |
address = address.replace(/:/g,''); | |
for (i=0; i<address.length; i+=2) { | |
if (i>0) { | |
binAddr = binAddr * 256; | |
} | |
binAddr += parseInt(address.substring(i,i+2), 16); | |
} | |
return binAddr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment