Monday, July 13, 2009

C# – Converting IP’s to Numbers and Numbers to IP’s in 2 lines of code

I don’t know why everywhere I searched had such complex implementation of this, but converting from a dotted IP to a number (integer) and back is quite straight forward with the help of the IPAddress and BitConverter classes.

Also, keep in mind that IP addresses are 32 bit integers; I’m not sure why people feel it’s necessary to use a decimal or double for this when a uint will work just fine!

/// 
/// Converts the IP address to an integer.
///

/// The IP address in dotted form.
///
public static uint ConvertIpToInteger(string ipAddress) {
return BitConverter.ToUInt32(IPAddress.Parse(ipAddress).GetAddressBytes().Reverse().ToArray(), 0);
}

///
/// Converts the integer to an IP address.
///

/// The IP address in integer form.
///
public static string ConvertIntegerToIp(uint ipAddress) {
return new IPAddress(BitConverter.GetBytes(ipAddress).Reverse().ToArray()).ToString();
}