What is the SQL Server equivalent of INET_ATON

前端 未结 3 1828
渐次进展
渐次进展 2021-02-10 06:18

As the question says what is the SQL Server equivalent of INET_ATON from mySql. The reason I need this is because i imported a IP data base from http://ipinfodb.com

3条回答
  •  南笙
    南笙 (楼主)
    2021-02-10 06:38

    I came here looking for the same, and applied Paul Dixon's solution.

    However, I noticed that we also have some IPv6 addresses, so I changed it a little bit:

    CREATE FUNCTION [dbo].[ip2int]
    (
        @ip VARCHAR(15) 
    )
    RETURNS INT
    AS
    BEGIN
    DECLARE @rv INT, 
            @o1 INT, 
            @o2 INT, 
            @o3 INT, 
            @o4 INT, 
            @base INT 
    
    IF ISNUMERIC(PARSENAME(@ip, 4) + '.0e0') =0 OR ISNUMERIC(PARSENAME(@ip, 3) + '.0e0') =0 OR ISNUMERIC(PARSENAME(@ip, 2) + '.0e0') =0 OR ISNUMERIC(PARSENAME(@ip, 1) + '.0e0') =0
        BEGIN
            set @rv = -2
        END
    ELSE
        BEGIN
        SELECT 
            @o1 = CONVERT(INT, PARSENAME(@ip, 4)), 
            @o2 = CONVERT(INT, PARSENAME(@ip, 3)), 
            @o3 = CONVERT(INT, PARSENAME(@ip, 2)), 
            @o4 = CONVERT(INT, PARSENAME(@ip, 1)) 
    
        IF (@o1 BETWEEN 0 AND 255) 
            AND (@o2 BETWEEN 0 AND 255) 
            AND (@o3 BETWEEN 0 AND 255) 
            AND (@o4 BETWEEN 0 AND 255) 
        BEGIN      
            SELECT @base = CASE 
                WHEN @o1 < 128 THEN 
                    (@o1 * 16777216) 
                ELSE 
                    -(256 - @o1) * 16777216 
                END 
    
            SET @rv = @base +  
                (@o2 * 65536) +  
                (@o3 * 256) + 
                (@o4) 
        END 
        ELSE 
            SET @rv = -1 
        END
        RETURN @rv 
    
    END
    

提交回复
热议问题