【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

转载于:https://www.cnblogs.com/clso/archive/2010/11/14/1876793.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值