【VB.NET】IP地址与INTEGER之间互转

分享最近写的一个IP地址与INT数据之间相互转换的函数,注意,该函数仅支持IPv4协议,不支持Ipv6。

 

下面的函数支持输出为INT或UINT类型,但实际上IP存储在INT和UINT内的数据在内存里的结构都是一样的,不过貌似SQL只支持INT结构的数据库,当然,请根据你自己的使用目的来选择函数。

 



  
    
Imports System.Text.RegularExpressions
Imports System.Net

#Region "IP与INT互转"

''' <summary> 将ip地址转换为int </summary>
Shared Function m_ip2int( ByVal ipads As String ) As Integer
Dim ret As Integer = 0 , b As Integer = 0
Dim mc As Match = Regex.Match(ipads, " (\d+)\.(\d+)\.(\d+)\.(\d+) " )
If Not mc.Success Then Return 0
For i As Integer = 1 To 4
ret
<<= 8
b
= mc.Groups(i).Value
If b > Byte .MaxValue Then Return 0
ret
+= b
Next
Return ret
End Function
Shared Function m_ip2int( ByVal ipads As IPAddress) As Integer
Dim bs As Byte () = ipads.GetAddressBytes
If bs.Length <> 4 Then Return 0
Dim ret As Integer = 0
For Each i As Byte In bs
ret
<<= 8
ret
+= i
Next
Return ret
End Function
''' <summary> 将int转换为ip地址 </summary>
Shared Function m_int2ip( ByVal ipint As Integer ) As String
Dim ret( 3 ) As Byte
Dim b As Integer = 255
For i As Integer = 0 To 3
ret(i)
= ipint And b
ipint
>>= 8
Next
Return String .Format( " {3}.{2}.{1}.{0} " , ret( 0 ), ret( 1 ), ret( 2 ), ret( 3 ))
End Function

''' <summary> 将ip地址转换为uint </summary>
Shared Function m_ip2uint( ByVal ip As String ) As UInteger
Dim bs As Byte () = IPAddress.Parse(ip).GetAddressBytes
Return CUInt(bs( 3 )) + (CUInt(bs( 2 )) << 8 ) + (CUInt(bs( 1 )) << 16 ) + (CUInt(bs( 0 )) << 24 )
End Function
''' <summary> 将uint转换为ip地址 </summary>
Shared Function m_uint2ip( ByVal ip As UInteger ) As String
Return New IPAddress(ip).ToString
End Function

''' <summary> 将ip地址转换为int </summary>
Shared Function m_IpToUInt( ByVal ip As String ) As UInteger
Dim bs As Byte () = IPAddress.Parse(ip).GetAddressBytes
Return CUInt(bs( 3 )) + (CUInt(bs( 2 )) << 8 ) + (CUInt(bs( 1 )) << 16 ) + (CUInt(bs( 0 )) << 24 )
End Function
''' <summary> 将uint转换为ip地址 </summary>
Shared Function m_UIntToIP( ByVal ip As UInteger ) As String
Return New IPAddress(ip).ToString
End Function

#End Region

你可能感兴趣的:(Integer)