2012/01/17

IPv4 Address convert to Integer (and reverse) (updated)

static Int64 IPv4StringToInt64(string ipv4String)
{
    Int64 ipInteger = 0;
    try
    {
        ipInteger = (long)(uint)IPAddress.NetworkToHostOrder(BitConverter.ToInt32(IPAddress.Parse(ipv4String).GetAddressBytes(), 0));
    }
    catch (Exception)
    { }

    return ipInteger;
}
static string IPv4Int64ToString(Int64 ipv4Int64)
{
    if (ipv4Int64 < 0)
        return "0.0.0.0";
    else if (ipv4Int64 < 4294967295)
        return IPAddress.Parse(ipv4Int64.ToString()).ToString();
    else
       return "255.255.255.255";
}
Usage:
Console.WriteLine("255.255.255.0 => " + IPv4StringToInt64("255.255.255.0"));
Console.WriteLine("4294967040 => " + IPv4Int64ToString(4294967040));

Reference: stackoverflow - How to convert an IPv4 address into a integer in C#?

1 comment: