13

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
  • 36,464
  • 39
  • 145
  • 218
Henry
  • 31,972
  • 19
  • 112
  • 214

2 Answers2

17

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
  • 273,340
  • 38
  • 408
  • 539
8

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

zwol
  • 121,956
  • 33
  • 219
  • 328
  • 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