This blog has, IMO, some great resources. Unfortunately, some of those resources are becoming less relevant. I'm still blogging, learning tech and helping others...please find me at my new home on

Friday, May 1, 2009

Converting an IP Address to Decimal

I am working through some interop code to manage a DHCP server from c#, which requires that I pass in IP addresses as their decimal value.

There are a number of ways to do this with loops and conversions and such but I wanted to write a way that actually uses some of the features of the .Net Framework.

This is a good example of using an anonymous delegate for iterating through a generic list (using the ForEach method) and building a hexadecimal string.  I use a simple formatting syntax to pad the lower-value bytes as required and then parse the entire string to get our decimal value.

private static string IpToDecimal(string ipAddress)
// split up the IP into octets and prep our string builder
List<string> octets = new List<string>(ipAddress.Split('.'));
    StringBuilder ipAsHex = new StringBuilder();

// loop through the octets and build up a hexidecimal string
octets.ForEach(delegate(string value)
    { ipAsHex.AppendFormat("{0:X2}", int.Parse(value)); });

// convert the hex to decimal and return
long decimalIP = long.Parse(ipAsHex.ToString(), NumberStyles.HexNumber);
    return decimalIP.ToString();

No comments:

Post a Comment