wiki.php 用Markdown写wiki是一种什么样的体验?

IP地址与INTEGER之间互转.md

最后更新于 2019-10-06 15:00:20

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

''' <summary>将ip地址转换为int</summary>
    Shared Function m_ip2int(ByVal ads As String) As Integer
        Dim ret As Integer = 0, b As Integer = 0
        Dim mc As Match = Regex.Match(ads, "(\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 ads As IPAddress) As Integer
        Dim bs As Byte() = ads.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 ip As Integer) As String
        Dim ret(3) As Byte
        Dim b As Integer = 255
        For i As Integer = 0 To 3
            ret(i) = ip And b
            ip >>= 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