我的IP范围字符串如下:
Dim IPRange as String = "192.168.0.1-192.168.0.100"
我使用代码来计算IP并添加到Arraylist中:
Dim beginIP() As Byte = IPAddress.Parse(IPRange.Split("-")(0)).GetAddressBytes
Array.Reverse(beginIP)
Dim endIP() As Byte = IPAddress.Parse(IPRange.Split("-")(1)).GetAddressBytes
Array.Reverse(endIP)
Dim IPbegin As UInt32 = BitConverter.ToUInt32(beginIP, 0)
Dim IPend As UInt32 = BitConverter.ToUInt32(endIP, 0)
Dim total as Integer = 0
Dim arr as New ArrayList()
For i As UInt32 = IPbegin To IPend
Dim IPbyte() As Byte = BitConverter.GetBytes(i)
Array.Reverse(IPbyte)
Dim IPCheck As String = New IPAddress(IPbyte).ToString
total += 1
arr.Add(IPCheck)
Next
但我拥有数千亿IP的IPRange,循环使我的应用程序非常慢。在这种情况下,如何加速此代码或其他方式来计算IP范围?
答案 0 :(得分:1)
使用您的代码
Dim stpw As Stopwatch = Stopwatch.StartNew
Dim IPRange As String = "192.168.0.0-192.200.255.255"
Dim beginIP() As Byte = IPAddress.Parse(IPRange.Split("-"c)(0)).GetAddressBytes
Array.Reverse(beginIP)
Dim endIP() As Byte = IPAddress.Parse(IPRange.Split("-"c)(1)).GetAddressBytes
Array.Reverse(endIP)
Dim IPbegin As UInt32 = BitConverter.ToUInt32(beginIP, 0)
Dim IPend As UInt32 = BitConverter.ToUInt32(endIP, 0)
Dim total As Integer = 0
For i As UInt32 = IPbegin To IPend
Dim IPbyte() As Byte = BitConverter.GetBytes(i)
Array.Reverse(IPbyte)
Dim IPCheck As String = New IPAddress(IPbyte).ToString
total += 1
Next
stpw.Stop()
Debug.WriteLine("{0:n0} in {1}", total, stpw.Elapsed)
具有更大的范围产生了这些结果。
00:00:00.37562082,162,688