Utilizo el siguiente método para convertir una dirección IP a dos 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;
}
Asegúrese de emitir su UInt64
s a Int64
s antes de ponerlos en la base de datos, o que obtendrá una ArgumentException
. Cuando recupere sus valores, puede devolverlos al UInt64
para obtener el valor sin firmar.
No necesito hacer lo contrario (es decir, convertir UInt64[2]
en una cadena IP) así que nunca construí un método para ello.
@ Bill: Usted está equivocado. No hay nada que diga que debe almacenar los bytes de una dirección IPv4 en un valor sin signo. Un Int32 tiene 32 bits como un UInt32, por lo que funciona perfectamente para almacenar cuatro bytes. – Guffa
Lo bueno @RBarryYoung no encontró este hilo ;-) http://stackoverflow.com/a/1385701/215068 IPv4 es de 4 bytes binarios, no "realmente un número de 32 bits". Los cuatro octetos de tres dígitos son solo una notación conveniente – EBarr
@EBarr: No, el número de IP en la versión 4 * es * un número de 32 bits, no es un número de 4 bytes. Mire una descripción del paquete IP, y verá que las direcciones son unidades únicas de 32 bits, no están separadas en cuatro valores de 8 bits. – Guffa