Formatting IPv6 as an int in C# and storing it in SQL Server

Guy picture Guy · Apr 21, 2009 · Viewed 16.3k times · Source

Under IPv4 I have been parsing the string representation of IP addresses to Int32 and storing them as INT in the SQL Server.

Now, with IPv6 I'm trying to find out if there's a standard or accepted way to parse the string representation of IPv6 to two Int64 using C#?

Also how are people storing those values in the SQL Server - as two fields of BIGINT?

Answer

Guffa picture Guffa · Apr 21, 2009

Just as an IPv4 address is really a 32 bit number, an IPv6 address is really a 128 bit number. There are different string representations of the addresses, but the actual address is the number, not the string.

So, you don't convert an IP address to a number, you parse a string representation of the address into the actual address.

Not even a decimal can hold a 128 bit number, so that leaves three obvious alternatives:

  • store the numeric value split into two bigint fields
  • store a string representation of the address in a varchar field
  • store the numeric value in a 16 byte binary field

Neither is as convenient as storing an IPv4 address in an int, so you have to consider their limitations against what you need to do with the addresses.