Tuesday, April 21, 2009

IP Address to Long and Log to IP Address in C#

Hi Friends,

sometimes in Socket programming we need to supply the "Long" data type version of IPAddress which is form "127.0.0.1".

So we need to convert this IP address to the Long format. Here two functions i have created which will convert IP address to Long and vice-verse.



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:

Post a Comment

Followers

My Google Reader