Henry
Henry

Reputation: 32905

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

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?

Upvotes: 12

Views: 6896

Answers (2)

zwol
zwol

Reputation: 140569

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

Upvotes: 8

Remus Rusanu
Remus Rusanu

Reputation: 294267

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

Upvotes: 16

Related Questions