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?

gotqn
  • 42,737
  • 46
  • 157
  • 243
Henry
  • 32,689
  • 19
  • 120
  • 221

2 Answers2

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).

Remus Rusanu
  • 288,378
  • 40
  • 442
  • 569
8

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

zwol
  • 135,547
  • 38
  • 252
  • 361
  • wouldn't it be just like binary(4) with 12x zero byte padding in front? – Henry Aug 25 '10 at 01:13
  • 3
    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). – zwol Aug 25 '10 at 01:17