Web Hosting Info

Search:

featured partner

The IP to Country Database

  Forum Topics : Development / IP dotted quad to numerical MS SQL User Defined Scalar Function
Submitted by rebby on Wed, 03/30/2005 - 14:32.
I just created this simple UDF for SQL 2000 and thought I'd share.

No error checking and other bells and whistles. If someone knows of a more efficient means for doing it, please let me know.

+++++++++++++++++++++++++++++++++++++++++++++
IF EXISTS (SELECT *
FROM sysobjects
WHERE name = N'GetNumericalIP')
DROP FUNCTION GetNumericalIP
GO

CREATE FUNCTION GetNumericalIP (@p_IPString varchar(15))
RETURNS bigint
AS
BEGIN
DECLARE
@l_IPNum bigint,
@l_dot1Pos int,
@l_dot2Pos int,
@l_dot3Pos int,
@l_addrNum1 bigint,
@l_addrNum2 bigint,
@l_addrNum3 bigint,
@l_addrNum4 bigint


/* parse the dotted quad */
SET @l_dot1Pos = CHARINDEX('.',@p_IPString,1)
SET @l_dot2Pos = CHARINDEX('.',@p_IPString,@l_dot1Pos + 1)
SET @l_dot3Pos = CHARINDEX('.',@p_IPString,@l_dot2Pos + 1)

SET @l_addrNum1 = CAST(SUBSTRING(@p_IPString,1,@l_dot1Pos - 1) AS bigint)
SET @l_addrNum2 = CAST(SUBSTRING(@p_IPString,@l_dot1Pos + 1,@l_dot2Pos - @l_dot1Pos - 1) AS bigint)
SET @l_addrNum3 = CAST(SUBSTRING(@p_IPString,@l_dot2Pos + 1,@l_dot3Pos - @l_dot2Pos - 1) AS bigint)
SET @l_addrNum4 = CAST(SUBSTRING(@p_IPString,@l_dot3Pos + 1,LEN(@p_IPString) - @l_dot3Pos) AS bigint)

/* do the calculation */
SET @l_IPNum = (@l_addrNum1 * 256 * 256 * 256) + (@l_addrNum2 * 256 * 256) + (@l_addrNum3 * 256) + @l_addrNum4

RETURN(@l_IPNum)
END
GO

GRANT EXEC ON spr_weblog_loadCountryMapData TO LogLoader
GO
Comment viewing options:
Select your preferred way to display the comments and click 'Save settings' to submit your changes.
Ammendment
Posted by rebby on Thu, 03/31/2005 - 06:51.
Actually, the permission line at the end should be...

GRANT EXEC ON GetNumericalIP TO PUBLIC
GO