0

我正在编写一个应用程序来存储请求来自的 IP 地址。这些 IP 地址将作为 a 存储varbinary(16)在我的数据库中。很明显,avarbinary(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)适当的长度。

谢谢!

4

2 回答 2

4

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

但是,相对而言,您提取字节的方式很奇怪。

请参阅IPAddress.GetAddressBytes()的文档

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

于 2013-02-27T15:11:31.270 回答
4
byte[] bytes = new byte[ipAddress.Length * sizeof(char)];

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

你所需要的只是ipAddress.GetAddressBytes()把它推到一个binary(16)

附带说明一下,您还可以使用 auniqueidentifier来存储 IPv6 地址,因为它们的长度相同。这些比搜索快得多varbinary

于 2013-02-27T15:12:36.657 回答