IP地址点分表示法与十进制表示法的转换

博客介绍了IP地址点分表示法与十进制表示法的转换方法。提供了Dot2LongIP和LongIP2Dot两个函数的代码实现,还补充了Ninputer效率更高的方法,同时提醒引入System.Runtime.InteropServices名称空间及注意LongIP类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

None.gif'
None.gif
        ' IP地址点分表示法转换为十进制表示法
None.gif
        '
ExpandedBlockStart.gifContractedBlock.gif
        Public Shared Function Dot2LongIP()Function Dot2LongIP(ByVal dotIP As StringAs Long
InBlock.gif            
' 使用正则表达式进行IP地址检验
InBlock.gif
            Dim subIP As String() = Split(dotIP, ".")
InBlock.gif            
'IP Address = w.x.y.z
InBlock.gif
            'IP Number = 16777216 * w + 65536 * x + 256 * y + z
InBlock.gif

InBlock.gif            Dot2LongIP 
= 16777216 * CLng(subIP(0)) + 65536 * CLng(subIP(1)) + 256 * CLng(subIP(2)) + CLng(subIP(3))
InBlock.gif
ExpandedBlockEnd.gif        
End Function

None.gif
ExpandedBlockStart.gifContractedBlock.gif        
Public Shared Function LongIP2Dot()Function LongIP2Dot(ByVal longIP As LongAs String
InBlock.gif            
'IP Address = w.x.y.z
InBlock.gif
            'IP Number = 16777216 * w + 65536 * x + 256 * y + z
InBlock.gif

InBlock.gif            
'w = int ( IP Number / 16777216 ) % 256
InBlock.gif
            'x = int ( IP Number / 65536    ) % 256
InBlock.gif
            'y = int ( IP Number / 256      ) % 256
InBlock.gif
            'z = int ( IP Number            ) % 256
InBlock.gif

InBlock.gif            
Dim dotIP As String
InBlock.gif            
Dim subIP As Integer
InBlock.gif
InBlock.gif            subIP 
= CInt(Fix(longIP / 16777216)Mod 256
InBlock.gif            dotIP 
= CStr(subIP) + "."
InBlock.gif

InBlock.gif
            subIP = CInt(Fix(longIP / 65536)Mod 256
InBlock.gif            dotIP 
+= CStr(subIP) + "."
InBlock.gif

InBlock.gif
            subIP = CInt(Fix(longIP / 256)Mod 256
InBlock.gif            dotIP 
+= CStr(subIP) + "."
InBlock.gif

InBlock.gif
            subIP = CInt(Fix(longIP Mod 256))
InBlock.gif            dotIP 
+= CStr(subIP)
InBlock.gif
InBlock.gif            
Return dotIP
ExpandedBlockEnd.gif        
End Function

2005-05-12补充,Ninputer:的方法确实很好,效率肯定比前面的计算方式要高.
None.gif<StructLayout(LayoutKind.Explicit)> _ 
ExpandedBlockStart.gifContractedBlock.gif
Public Structure IPConvertStructure IPConvert 
InBlock.gif  
<FieldOffset(0)> Public LongIP As Long 
InBlock.gif  
<FieldOffset(0)> Public DotIP0 As Byte 
InBlock.gif  
<FieldOffset(1)> Public DotIP1 As Byte 
InBlock.gif  
<FieldOffset(2)> Public DotIP2 As Byte 
InBlock.gif  
<FieldOffset(3)> Public DotIP3 As Byte 
ExpandedBlockEnd.gif
End Structure
 
None.gif
注意需要引入名称空间System.Runtime.InteropServices,并且LongIP的类型确实是Long,而不是Integer.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值