簡體   English   中英

IPv6 IP地址的字節數組大小

[英]Byte Array Size for a IPv6 IP Address

我正在寫一個應用程序,該應用程序將存儲請求來源的IP地址。 這些IP地址將以varbinary(16)形式存儲在我的數據庫中。 顯而易見, 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)的大小更改為適當的長度。

謝謝!

IPv6地址空間為128位。 因此,任何IPv6地址都可以使用16個字節表示。 因此,varbinary(16)是正確的。

但是,就字節而言,提取字節的方式很奇怪。

請參閱IPAddress.GetAddressBytes()的文檔

(看起來您可能還需要IPAddress.Parse()

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

這看起來像是C程序員編寫的東西,您無需執行任何操作。

您需要的只是ipAddress.GetAddressBytes()並將其推入binary(16)

附帶說明,由於IPv6地址的長度相同,因此也可以使用uniqueidentifier來存儲它們。 這些搜索比varbinary快得多

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM