如题,纯练手,意义不大。
代码:
static void Main(string[] args) { string ip1, ip2; string[] ip1s, ip2s; int[] int_ip1s = new int[4], int_ip2s = new int[4]; int step = 256, t, i; bool flag; Console.WriteLine("起始ip:"); ip1 = Console.ReadLine(); Console.WriteLine("终止ip:"); ip2 = Console.ReadLine(); ip1s = ip1.Split('.'); ip2s = ip2.Split('.'); for (i = 0; i < 4; i++) { int_ip1s[i] = int.Parse(ip1s[i]); int_ip2s[i] = int.Parse(ip2s[i]); } do { flag = false; Console.WriteLine($"{int_ip1s[0]}.{int_ip1s[1]}.{int_ip1s[2]}.{int_ip1s[3]}"); t = int_ip1s[3] + 1; i = 3; while (i > 0) { int_ip1s[i--] = t % step; int_ip1s[i] += t / step; t = int_ip1s[i]; } for (i = 0; i < 4; i++) { if (int_ip1s[i] != int_ip2s[i]) { flag = true; break; } } } while (flag); Console.WriteLine($"{int_ip1s[0]}.{int_ip1s[1]}.{int_ip1s[2]}.{int_ip1s[3]}"); Console.WriteLine("ok"); Console.ReadKey(); }
效果:
网络上有另外的代码,也提供了不错的思路:
引自https://www.cnblogs.com/luxiaoxun/p/3376682.html,感谢作者!
public static long IpToInt(string ip) { char[] separator = new char[] { '.' }; string[] items = ip.Split(separator); return long.Parse(items[0]) << 24 | long.Parse(items[1]) << 16 | long.Parse(items[2]) << 8 | long.Parse(items[3]); } public static string IntToIp(long ipInt) { StringBuilder sb = new StringBuilder(); sb.Append((ipInt >> 24) & 0xFF).Append("."); sb.Append((ipInt >> 16) & 0xFF).Append("."); sb.Append((ipInt >> 8) & 0xFF).Append("."); sb.Append(ipInt & 0xFF); return sb.ToString(); }
ip转换成整数,就可以利用条件判断,逐次加一完成操作了。
对位运算不熟悉的同学,也可以用乘(左移)除(右移)、取余(与)来完成。