Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Community Wiki

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Navigation

Google Ads

Converting IP Addresses Between Bigint and Varchar

From Wiki

Jump to: navigation, search

Before we start with code let us take a sample IP address, does 127.0.0.1 look familiar? Yes that is your local IP address.

Here it is in decimal and binary format
127 0 0 1
01111111 00000000 00000000 00000001

Now to convert, you would take the first value
add the second value + 256
add the third value + (256 * 256) = 65536
add the fourth value + (256 * 256 * 256) =16777216

So in our case the select would be

  1. SELECT
  2. 1 +
  3. 0 * 256 +
  4. 0 * 65536 +
  5. 127 * 16777216

which is 2130706433

So to convert from IP Adress to integer is very simple, you use PARSENAME to split it up and do the math. Here is the function for that

  1. CREATE FUNCTION dbo.IPAddressToInteger (@IP AS VARCHAR(15))
  2. RETURNS BIGINT
  3. AS
  4. BEGIN
  5.  RETURN (CONVERT(BIGINT, PARSENAME(@IP,1)) +
  6.          CONVERT(BIGINT, PARSENAME(@IP,2)) * 256 +
  7.          CONVERT(BIGINT, PARSENAME(@IP,3)) * 65536 +
  8.          CONVERT(BIGINT, PARSENAME(@IP,4)) * 16777216)
  9.  
  10. END
  11. GO

But how do you get 127.0.0.1 out of 2130706433? It is the reverse of what we did before (surprise) so instead of multiplying we will be dividing. The "modulo 256" part simply removes the bytes above the one we're interested in so we only get numbers in the correct range of 0 - 255.

  1. CREATE FUNCTION dbo.IntegerToIPAddress (@IP AS BIGINT)
  2. RETURNS VARCHAR(15)
  3. AS
  4. BEGIN
  5. RETURN
  6.    CONVERT (VARCHAR, @IP / 16777216) + '.'
  7.    + CONVERT(VARCHAR, @IP / 65536 % 256) + '.'
  8.    + CONVERT(VARCHAR, @IP / 256 % 256) + '.'
  9.    + CONVERT(VARCHAR, @IP % 256)
  10. END

Now let's try this out, first run this

  1. SELECT dbo.IPAddressToInteger('127.0.0.1')

That returns 2130706433 Now run this

  1. SELECT dbo.IntegerToIPAddress(2130706433)

That returns 127.0.0.1


Contributed by: --SQLDenis 17:59, 5 October 2008 (GMT)


Part of SQL Server Programming Hacks

Section Handy tricks

596 Rating: 1.9/5 (10 votes cast)