Thursday, December 20, 2007

IP address to long and Long value to IP address string

this methods are depricated from framework 2.0 but still we need way to do this...so this is the way...

public static uint IPAddressToLong(string IPAddr)
{
IPAddress oIP = IPAddress.Parse(IPAddr);
byte[] byteIP = oIP.GetAddressBytes();


uint ip = (uint)byteIP[0] << 24;
ip += (uint)byteIP[1] << 16;
ip += (uint)byteIP[2] << 8;
ip += (uint)byteIP[3];

return ip;
}

public static string LongToIPAddress(uint ipLong)
{
//string ipAddress = string.Empty;
byte[] addByte = new byte[4];

addByte[0] = (byte)((ipLong >> 24) & 0xFF);
addByte[1] = (byte)((ipLong >> 16) & 0xFF);
addByte[2] = (byte)((ipLong >> 8) & 0xFF);
addByte[3] = (byte)((ipLong >> 0) & 0xFF);

return addByte[0].ToString() + "." + addByte[1].ToString() + "." + addByte[2].ToString() + "." + addByte[3].ToString();
}

No comments: