Formatting IPv6 as an int in C# and storing it in SQL Server

前端 未结 5 2223
无人及你
无人及你 2020-12-15 05:00

Under IPv4 I have been parsing the string representation of IP addresses to Int32 and storing them as INT in the SQL Server

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-15 05:41

    I use the following method for converting an IP address to two UInt64s (C# 3.0).

    /// 
    /// Converts an IP address to its UInt64[2] equivalent.
    /// For an IPv4 address, the first element will be 0,
    /// and the second will be a UInt32 representation of the four bytes.
    /// For an IPv6 address, the first element will be a UInt64
    /// representation of the first eight bytes, and the second will be the
    /// last eight bytes.
    /// 
    /// The IP address to convert.
    /// 
    private static ulong[] ConvertIPAddressToUInt64Array(string ipAddress)
    {
        byte[] addrBytes = System.Net.IPAddress.Parse(ipAddress).GetAddressBytes();
        if (System.BitConverter.IsLittleEndian)
        {
            //little-endian machines store multi-byte integers with the
            //least significant byte first. this is a problem, as integer
            //values are sent over the network in big-endian mode. reversing
            //the order of the bytes is a quick way to get the BitConverter
            //methods to convert the byte arrays in big-endian mode.
            System.Collections.Generic.List byteList = new System.Collections.Generic.List(addrBytes);
            byteList.Reverse();
            addrBytes = byteList.ToArray();
        }
        ulong[] addrWords = new ulong[2];
        if (addrBytes.Length > 8)
        {
            addrWords[0] = System.BitConverter.ToUInt64(addrBytes, 8);
            addrWords[1] = System.BitConverter.ToUInt64(addrBytes, 0);
        }
        else
        {
            addrWords[0] = 0;
            addrWords[1] = System.BitConverter.ToUInt32(addrBytes, 0);
        }
        return addrWords;
    }
    

    Make sure you cast your UInt64s to Int64s before you put them into the database, or you'll get an ArgumentException. When you get your values back out, you can cast them back to UInt64 to get the unsigned value.

    I don't have a need to do the reverse (i.e. convert a UInt64[2] to an IP string) so I never built a method for it.

提交回复
热议问题