SQL Server INET_ATON IP Address + CIDR

Most IT folk would understand that an IP Address is a 4-octset set – eg. 192.168.53.123

There’s another piece that is the subnet mask – eg.  255.255.252.0

These are usually managed as numerical values – BIGINT values (Int64).

Within MySQL, you can determine the IP Address to/from a number using the functions INET_ATON and INET_NTOA.

For an equivalent in SQL Server – you can use the following UDF’s :

Integer to IP Address :

CREATE FUNCTION [dbo].[IntegerToIPAddress] (@IP AS bigint)
RETURNS varchar(15)
AS
BEGIN
 DECLARE @Octet1 bigint
 DECLARE @Octet2 tinyint
 DECLARE @Octet3 tinyint
 DECLARE @Octet4 tinyint
 DECLARE @RestOfIP bigint
 
 SET @Octet1 = @IP / 16777216
 SET @RestOfIP = @IP - (@Octet1 * 16777216)
 SET @Octet2 = @RestOfIP / 65536
 SET @RestOfIP = @RestOfIP - (@Octet2 * 65536)
 SET @Octet3 = @RestOfIP / 256
 SET @Octet4 = @RestOfIP - (@Octet3 * 256)
 
 RETURN(CONVERT(varchar, @Octet1) + '.' +
        CONVERT(varchar, @Octet2) + '.' +
        CONVERT(varchar, @Octet3) + '.' +
        CONVERT(varchar, @Octet4))
END

IP Address to Integer

CREATE FUNCTION [dbo].[IPAddressToInteger] (@IP AS varchar(15))
RETURNS bigint
AS
BEGIN
 RETURN (CONVERT(bigint, PARSENAME(@IP,1)) +
         CONVERT(bigint, PARSENAME(@IP,2)) * 256 +
         CONVERT(bigint, PARSENAME(@IP,3)) * 65536 +
         CONVERT(bigint, PARSENAME(@IP,4)) * 16777216)
 
END

Yet another piece of the puzzle is related to a CIDR – which looks like this :  192.30.250.00/18

It’s an acronym for “Classless Inter-Domain Routing” – I had to look it up too…!

I’ve created another function that determines the “/18” for a given numeric sequence (in T-SQL).

CREATE FUNCTION [dbo].[CIDRFromMask] (@mask AS BIGINT)
RETURNS VARCHAR(5)
AS
BEGIN

	 DECLARE @maskCalc BIGINT
	 SELECT @maskCalc = dbo.IPAddressToInteger('255.255.255.255') - @mask + 1

	 DECLARE @logCalc int
	 SELECT @logCalc = (32 - LOG(@maskCalc, 2))

	 RETURN '/' + CAST(@logCalc AS VARCHAR(5))

END

This helped me with the retrieval of an IP Address – and CIDR – fairly complex, but easy to use in the end – eg.  255.255.252.0/22

select dbo.IntegerToIPAddress('4294966272') + dbo.CIDRFromMask('4294966272')

image

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s