How to store both IPv4 or IPv6 in single column in SQL Server?
Asked Answered
T

2

12

Should I use binary(16) or varbinary(16)?

I know I can use getAddress() in java.net.InetAddress (Java) or System.Net.IPAddress (C#) to get a byte[] representation of both IPv4 and IPv6, but if I need to insert IPv4 i.e. binary(4) into a binary(16) field in SQL Server, do I need to worry about padding or anything?

Travers answered 24/8, 2010 at 23:52 Comment(0)
S
16

IF you store a binary(4) in a binary(16) column you'll get back, when you read it, a padded value of length 16. If you want to have dynamic length you must use a varbinary(16). This type retains the length of the data inserted, at the cost of adding extra 2 bytes on-disk (the actual length).

Sheliasheline answered 25/8, 2010 at 0:2 Comment(4)
Since I expect majority of the IP will still be in IPv4, I guess varbinary(16) makes sense.Travers
And the cost of creating a variable length fieldHouri
For the exact cost details see msdn.microsoft.com/en-us/library/ms178085.aspx and/or sqlskills.com/blogs/paul/post/…Sheliasheline
Remus Rusanu, would u use binary(16) or varbinary(16)?Travers
J
8

Use v4-in-v6 address embedding to convert your ipv4 addresses to ipv6 format; then you can treat them all identically.

Jemine answered 25/8, 2010 at 0:11 Comment(2)
wouldn't it be just like binary(4) with 12x zero byte padding in front?Travers
Presumably you expect some of the entries in this database column to be actual ipv6 addresses. The point of v4-in-v6 embedding is that more of your application code won't have to care about the difference (it can just pretend it has nothing but v6 addresses).Jemine

© 2022 - 2024 — McMap. All rights reserved.