本文介绍了IPv6缩写(零块压缩)逻辑.我正在使用C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个完整的未压缩IP地址2001:0008:0000:CD30:0000:0000:0000:0101我需要这样压缩2001:8:0:CD30 :: 101但是我只能像这样压缩块中的零2001:8:0:CD30:0:0:0:101使用此代码

This is a complete un compressed IP address 2001:0008:0000:CD30:0000:0000:0000:0101I need to compress it like this2001:8:0:CD30::101But i was only able to compress the zeroes in blocks like this2001:8:0:CD30:0:0:0:101using 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;
        }

我正在使用c#,但我只需要有关如何删除整个零块的编程逻辑,问题是在ip中可能会有超过1组包含所有零的块,但只能缩写一个.

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.

推荐答案

比我想象的要复杂得多,但是在这里,您可以使用正则表达式来做到这一点:

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");
        }

这篇关于IPv6缩写(零块压缩)逻辑.我正在使用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 23:00