I'm not the best with JavaScript. I was able to get a nice ipv62long()
function working in PHP awhile back and was able to help someone with their question regarding it. But posting to PHP just to get a result is pretty nasty in my opinion. Can a function like this be achieved in JavaScript? What functions am I looking for to achieve it? I've tried countless searches and they always feedback to PHP examples.
function ipv62long( $ip ) {
$binNum = '';
foreach ( unpack('C*', inet_pton( $ip ) ) as $byte ) {
$binNum .= str_pad( decbin( $byte ), 8, "0", STR_PAD_LEFT );
}
return base_convert( ltrim($binNum, '0' ), 2, 10 );
}
$ip = ipv62long(urldecode('2001%3a0%3a9d38%3a6abd%3a248d%3a2ee4%3a3f57%3afd26'));
echo $ip;
echo '<p>' . long2ip( $ip ) . '</p>';
Just for kicks I did it in PHP too:)
Explaining the PHP a bit more: I use inet_pton to get a binary value, then by using OR and bit shifting I build a new long values (4 bytes).
Since inet_pton returns a structure, I use ord to get the decimal value of the data.
Then I invert the long using NOT and pass it to long2ip...
<?PHP
$data = inet_pton(urldecode('2001%3a0%3a9d38%3a6abd%3a248d%3a2ee4%3a3f57%3afd26'));
// 192.168.2.217
// build a long 4 bytes using binary ORing
$ip_as_long = ord($data[15]);
$ip_as_long |= ord($data[14]) << 8;
$ip_as_long |= ord($data[13]) << 16;
$ip_as_long |= ord($data[12])<<24;
echo long2ip(~$ip_as_long);
?>
Javascript
<script>
var value = '2001:0:9d38:6abd:248d:2ee4:3f57:fd26';
var split_str = value.split(':');
value = split_str[6] + split_str[7];
var ip_1 = ~parseInt(value.substring(0,2),16) & 0xFF;
var ip_2 =~parseInt(value.substring(2,4),16) & 0xFF;
var ip_3 =~parseInt(value.substring(4,6),16) & 0xFF;
var ip_4 =~parseInt(value.substring(6,8),16) & 0xFF;
alert(ip_1+'.'+ip_2+'.'+ip_3+'.'+ip_4);
</script>
enjoy.