简体   繁体   中英

How can i strip ipv6 address in javascript?

0000:0000:0000:0000:0000:0000:0000:0000
0000:0000:0000:0000:FFFF:0000:0002:AC11

How can i effectively strip the 0000 parts from the above ipv6 address to convert it to :

0000
FFFF:0000:0002:AC11

You can use:

 "0000:0000:0000:0000:FFFF:0000:0002:AC11".replace(/^(0000:)+/)

The pattern is anchored on the start of the string, and removes repeating occurences of 0000: from there.


Demo : https://regex101.com/r/jU7qM5/1

//ip is a string
function stripIP(ip){
   var result = "";
   var arr = ip.match(/(?:0000:)*(.*)/);
   if(arr[1]){
    result = arr[1];
   }
 return result;
}

As http://tools.ietf.org/html/rfc4291#section-2.2 and http://tools.ietf.org/html/rfc5952#section-4.2 explain just stripping out those "0000:" can yield a not valid IPv6 representation.

The "::" substitution should not be made for just one group of ceroes, can be made only once in the address and leading 0s stripping have to be made inside each digits group. Also IPv4 mapping should be take in account.

I'd use: (ip is 16 chars HEX string representation of IPv6 address)

function ip_notation(ip){
  var ip=ip.toLowerCase();
  //Watch out IPv6/IPv4 addresses notation
  //::ffff:XXX.XXX.XXX.XXX vs ::ffff:xxxx:xxxx
  if(ip.substr(0,24)=='00000000000000000000ffff' ){
    ip4= (ip.substr(24));
    ip4=ip4.match(/.{1,2}/g);
    for(k=0;k<4;k++){ip4[k]=parseInt(ip4[k],16);}
    ip='::ffff:'+ ip4.join('.');
    return ip;
  }
  field=ip.match(/.{1,4}/g);//Cut string in 4 digits fields
  //Find the longest ceroes fields group (maybe could be done with a regex)
  var max_ceroes_fields=0;
  var ceroes_fields=0;
  for(k=0;k<8;k++){
    if(field[k] == '0000') { //All '0' field
      ceroes_fields++;
      if( ceroes_fields > max_ceroes_fields ) { 
        max_ceroes_fields = ceroes_fields;
      }
    }else{//Not all '0' field
      ceroes_fields = 0;
    }
  }
  ip=field.join(":");//makes a string again, now with 4 digit groups
  //replace the longest ceroes group with "::"
  if(max_ceroes_fields>1) {
    var ceroes=(":0000".repeat(max_ceroes_fields)).substr(1);
    ip=ip.replace(ceroes,':');
    //Works fine if it is at the start or end, but produces ":::" in the middle
    ip=ip.replace(':::','::');
  }
  //Strip leading ceroes of fields
  ip.replace(/^(0){1,3}/,'');
  return ip;
}

Try the ip6 npm package: https://www.npmjs.com/package/ip6

ip6 helps to normalize, abbreviate, divide subnets, generate random subnets/hosts and calculate range of size of an IPv6 subnet.

let ip6 = require('ip6');
console.log(ip6.abbreviate('2001:0001:0000:0001:0000:0000:0000:0001'));
// 2001:1:0:1::1 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM