完善SQL二进制到IP地址字符串转换

时间:2010-09-08 08:46:11

标签: sql sql-server

我们使用二进制(16)字段来存储IP地址。我们这样做是因为它可以容纳IPv4和IPv6地址,并且很容易与.Net IPAddress类一起使用。

但是我创建了以下SQL函数来将二进制地址转换为IP地址字符串以进行报告。

CREATE FUNCTION fn_ConvertBinaryIPAddressToString
(
    @binaryIP binary(16)
)
RETURNS nvarchar(39)
AS
BEGIN
    DECLARE @ipAsString nvarchar(39)

    -- Is IPv4
    IF (substring(@binaryIP, 5, 1) = 0x00)  <-- Is there a better way?
    BEGIN

        SELECT @ipAsString = CAST(CAST(substring(@binaryIP, 1, 1) AS int) AS nvarchar(3)) + '.' +
        CAST(CAST(substring(@binaryIP, 2, 1) AS int) AS nvarchar(3)) + '.' +
        CAST(CAST(substring(@binaryIP, 3, 1) AS int) AS nvarchar(3)) + '.' +
        CAST(CAST(substring(@binaryIP, 4, 1) AS int) AS nvarchar(3))

    END
    ELSE
    BEGIN
    -- Is IPv6
        -- taken and modified from http://support.microsoft.com/kb/104829
        DECLARE @i int
        DECLARE @length int
        DECLARE @hexstring char(16)

        SELECT @ipAsString = ''
        SELECT @i = 1
        SELECT @length = 16
        SELECT @hexstring = '0123456789ABCDEF'

        WHILE (@i <= @length)
        BEGIN
            DECLARE @tempint int
            DECLARE @firstint int
            DECLARE @secondint int

            SELECT @tempint = convert(int, substring(@binaryIP,@i,1))
            SELECT @firstint = floor(@tempint/16)
            SELECT @secondint = @tempint - (@firstint*16)

            SELECT @ipAsString = @ipAsString + substring(@hexstring, @firstint+1, 1) + substring(@hexstring, @secondint+1, 1)

            IF (@i % 2 = 0)
                SELECT @ipAsString = @ipAsString + ':'

            SELECT @i = @i + 1
       END
    END

    -- Return the result of the function
    RETURN @ipAsString

END
GO

如果5字节为0,我认为它是IPv4地址。这是一个安全的假设吗?是否更好地检查所有剩余的零字节还是有更好的方法?

编辑删除了不必要的演员

1 个答案:

答案 0 :(得分:5)

我会说你也应该存储地址族,要么在字节数组中编码,要么作为单独的列编码。如果将16个字节传递给IPAddress构造函数,它将构造为IPv6地址,因此您还需要检查代码以确定地址族。看起来更容易(并且不依赖于关于IPv6地址的字节的假设)来直接保存这些信息。

或者使用varbinary(16),然后可以检查(length = 4 =&gt; IPv4地址)的长度