IPv6 IP地址的字节数组大小

时间:2013-02-27 15:07:18

标签: c# byte ipv6

我正在编写一个应用程序,用于存储请求来自的IP地址。这些IP地址将作为varbinary(16)存储在我的数据库中。很明显varbinary(16)的大小不合适。目前,我正在使用以下代码将请求的IP地址转换为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?

我注意到字节长度为26.我的问题是,如果我需要支持IPv6地址,那么字节的最大大小是多少?我需要知道将varbinary(16)的大小更改为适当的长度。

谢谢!

2 个答案:

答案 0 :(得分:4)

IPv6地址空间为128位。因此,任何IPv6地址都可以使用16个字节表示。因此,varbinary(16)是正确的。

但是,你提取字节的方式是,奇怪的。

请参阅IPAddress.GetAddressBytes()

的文档

(看起来您可能还需要IPAddress.Parse()

答案 1 :(得分:4)

byte[] bytes = new byte[ipAddress.Length * sizeof(char)];

这看起来像是由C程序员编写的,你不需要做任何这些。

您需要的只是ipAddress.GetAddressBytes()并将其推送到binary(16)

作为旁注,您还可以使用uniqueidentifier来存储IPv6地址,因为它们的长度相同。搜索速度比varbinary

快得多