I'm writing an app that will store the IP Addresses of where requests are coming from. Those IP Addresses will be stored as a varbinary(16)
in my database. Its become apparent that a varbinary(16)
is not the proper size. Currently, I'm using the following code to get the IP Address of a request into a byte[];
HttpRequestMessage request = GetRequestMessage();
string ipAddress = string.Empty;
if (request.Properties.ContainsKey("MS_HttpContext"))
{
ipAddress = ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
}
else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
{
RemoteEndpointMessageProperty property = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];
ipAddress = property.Address;
}
byte[] bytes = new byte[ipAddress.Length * sizeof(char)];
System.Buffer.BlockCopy(ipAddress.ToCharArray(), 0, bytes, 0, bytes.Length);
// What is the maximum size of bytes?
I've noticed that bytes has a length of 26. My question is, what is the largest size that bytes can be if I need to support IPv6 addresses? I need to know to change the size of my varbinary(16)
to the appropriate length.
Thank you!
varbinary(16)
, but since you know you want to store exactly 16 bytes, you can usebinary(16)
instead and lose the overhead of the variable length. Or as @PhonicUK stated,uniqueidentifier
works as well. – Joe EnosSystem.Net.IPAddress
, an instance of the correct family will be produced. From the docs: "If the length of address is 4, IPAddress(Byte[]) constructs an IPv4 address; otherwise, an IPv6 address with a scope of 0 is constructed." Writing code that uses IPAddress helps with writing code that works fine with both IPv4 and IPv6. – tomfanning