-->

IPv6 Abbreviation(zero blocks compression) logic.

2019-06-01 05:06发布

问题:

This is a complete un compressed IP address 2001:0008:0000:CD30:0000:0000:0000:0101 I need to compress it like this 2001:8:0:CD30::101 But i was only able to compress the zeroes in blocks like this 2001:8:0:CD30:0:0:0:101 using this code

 string output = "";
        string a = textBox1.Text;
        if (a.Length != 39  )
            MessageBox.Show("Invalid IP please enter the IPv6 IP in this format 6cd9:a87a:ad46:0005:ad40:0000:5698:8ab8");
        else
        {
            for (int i = 0; i < a.Length; i++)
            {
                if ((a[i] >= '1' && a[i] <= '9') || (Char.ToLower(a[i]) >= 'a' && Char.ToLower(a[i]) <= 'f') || ((i + 1) % 5 == 0 && a[i] == ':'))
                {
                    output = output + a[i];
                }
                else if ((a[i]=='0' && a[i-1]==':') || (a[i]=='0' && a[i-1]=='0' && a[i-2]==':') || (a[i]=='0' && a[i-1]=='0' && a[i-2]=='0' && a[i-3]==':')) 
                {

                }
                else if (a[i] == '0')
                {
                    output = output + a[i];
                }

                else
                {
                    MessageBox.Show("Invalid IP please enter the IPv6 IP in this format 6cd9:a87a:ad46:0005:ad40:0000:5698:8ab8");
                }
            }

            textBox2.Text = output;
        }

Im using c# but i only need the programming logic about how can whole blocks of zeroes be deleted the problem is there could be more then 1 group of blocks containing all zeros in an ip but only one should be abbreviated.

回答1:

Was far more tricky than I expected, but here you got the way to do it with regular expressions:

        private static string Compress(string ip)
        {
            var removedExtraZeros = ip.Replace("0000","*");

            //2001:0008:*:CD30:*:*:*:0101
            var blocks = ip.Split(':');

            var regex = new Regex(":0+");
            removedExtraZeros = regex.Replace(removedExtraZeros, ":");


            //2001:8:*:CD30:*:*:*:101

            var regex2 = new Regex(":\\*:\\*(:\\*)+:");
            removedExtraZeros = regex2.Replace(removedExtraZeros, "::");
            //2001:8:*:CD30::101

            return removedExtraZeros.Replace("*", "0");
        }