CIDR计算
public static string IPV4CIDR(string ipstart, string ipend) { var sl = ipstart.Split('.'); var el = ipend.Split("."); StringBuilder sbs = new StringBuilder(); StringBuilder sbe = new StringBuilder(); List<char> cs = new List<char>(); List<char> ce = new List<char>(); foreach (var s in sl) { var t = Num2Str(int.Parse(s)); sbs.Append(t.ToString()); cs.AddRange(t.ToCharArray()); //Console.WriteLine($"{s}={t}"); } foreach (var s in el) { var t = Num2Str(int.Parse(s)); sbe.Append(t.ToString()); ce.AddRange(t.ToCharArray()); //Console.WriteLine($"{s}={t}"); } int cidr = 0; for (; cidr < 32; cidr++) { if (cs[cidr] != ce[cidr]) { break; } } List<string> iplist = new List<string>(); int st = 0; do { int step = cidr - st > 8 ? 8 : (cidr - st); var one = sbs.ToString().Substring(0, step); var n = Str2Num(one.PadRight(8, '0')); iplist.Add(n.ToString()); sbs = new StringBuilder(sbs.ToString().Substring(step, sbs.Length - one.Length)); st += step; } while (st < cidr); switch (iplist.Count) { case 1: iplist.AddRange("0,0,0".Split(',')); break; case 2: iplist.AddRange("0,0".Split(',')); break; case 3: iplist.Add("0"); break; } Console.WriteLine($"{string.Join('.',iplist.ToArray())}/{cidr}"); //Console.WriteLine(sbs.ToString()); //Console.WriteLine(sbe.ToString()); //Console.WriteLine(cidr); return string.Empty; } public static string Num2Str(int s) { return Convert.ToString(s, 2).PadLeft(8, '0'); } public static int Str2Num(string s) { return Convert.ToInt32(s, 2); }