IPv6 IP地址的字节数组大小 [英] Byte Array Size for a IPv6 IP Address

查看:98
本文介绍了IPv6 IP地址的字节数组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个应用程序,该应用程序将存储请求来源的IP地址。这些IP地址将作为 varbinary(16)存储在我的数据库中。显而易见, varbinary(16)的大小不合适。目前,我正在使用以下代码将请求的IP地址转换为byte [];

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?

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

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.

谢谢!

推荐答案

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

这看起来像是C程序员编写的东西,您无需执行任何操作。

This looks like something written by a C programmer, you don't need to do any of this.

所有您需要的是 ipAddress.GetAddressBytes()并将其放入 binary( 16)

All you need is ipAddress.GetAddressBytes() and shove that in a binary(16)

另外,您还可以使用 uniqueidentifier 进行存储IPv6地址,因为它们的长度相同。这些搜索要比 varbinary

As a side note, you can also use a uniqueidentifier to store IPv6 addresses since they are the same length. These are much faster to search with than a varbinary

这篇关于IPv6 IP地址的字节数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆