Tôi sử dụng phương pháp sau để chuyển đổi địa chỉ IP thành hai UInt64
s (C# 3.0).
/// <summary>
/// Converts an IP address to its UInt64[2] equivalent.
/// For an IPv4 address, the first element will be 0,
/// and the second will be a UInt32 representation of the four bytes.
/// For an IPv6 address, the first element will be a UInt64
/// representation of the first eight bytes, and the second will be the
/// last eight bytes.
/// </summary>
/// <param name="ipAddress">The IP address to convert.</param>
/// <returns></returns>
private static ulong[] ConvertIPAddressToUInt64Array(string ipAddress)
{
byte[] addrBytes = System.Net.IPAddress.Parse(ipAddress).GetAddressBytes();
if (System.BitConverter.IsLittleEndian)
{
//little-endian machines store multi-byte integers with the
//least significant byte first. this is a problem, as integer
//values are sent over the network in big-endian mode. reversing
//the order of the bytes is a quick way to get the BitConverter
//methods to convert the byte arrays in big-endian mode.
System.Collections.Generic.List<byte> byteList = new System.Collections.Generic.List<byte>(addrBytes);
byteList.Reverse();
addrBytes = byteList.ToArray();
}
ulong[] addrWords = new ulong[2];
if (addrBytes.Length > 8)
{
addrWords[0] = System.BitConverter.ToUInt64(addrBytes, 8);
addrWords[1] = System.BitConverter.ToUInt64(addrBytes, 0);
}
else
{
addrWords[0] = 0;
addrWords[1] = System.BitConverter.ToUInt32(addrBytes, 0);
}
return addrWords;
}
Hãy chắc chắn rằng bạn cast UInt64
của bạn để Int64
s trước khi bạn đặt chúng vào cơ sở dữ liệu, hoặc bạn sẽ nhận được một ArgumentException
. Khi bạn lấy lại các giá trị của mình, bạn có thể truyền trở lại UInt64
để nhận giá trị chưa ký.
Tôi không cần phải làm ngược lại (tức là chuyển đổi UInt64[2]
thành chuỗi IP) để tôi không bao giờ tạo phương thức cho nó.
Nguồn
2009-10-29 21:19:39
@ Bill: Bạn đang nhầm lẫn. Không có gì mà nói rằng bạn phải lưu trữ các byte của một địa chỉ IPv4 trong một giá trị unsigned. Int32 có 32 bit giống như UInt32, vì vậy nó hoạt động tốt để lưu trữ bốn byte. – Guffa
Điều tốt @RBarryYoung không tìm thấy chủ đề này ;-) http://stackoverflow.com/a/1385701/215068 IPv4 là 4 byte nhị phân, không phải "thực sự là một số 32 bit". Bốn octet ba chữ số chỉ là một ký hiệu thuận tiện – EBarr
@EBarr: Không, số IP trong phiên bản 4 * là * một số 32 bit, nó không phải là số 4 byte. Hãy xem mô tả về gói IP và bạn thấy rằng các địa chỉ là các đơn vị đơn 32 bit, chúng không được tách thành bốn giá trị 8 bit. – Guffa