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 http://www.jameschambers.com/.

Friday, May 1, 2009

Oh…Brainwaves!

Just occurred to me that you can also fairly easily convert the IP if you shift the values as you walk across the octets. 

Here’s a simpler version of the same method.  I’m not using any of the formatting, but I still employ the anon delegate on the generic list. 

private static string IpToDecimal(string ipAddress)
{
// split up the IP into octets and prep our string builder
List<string> octects = new List<string>(ipAddress.Split('.'));
long decIP = 0;
int shift = 3;

// loop through the octets and compute the decimal version
octects.ForEach(delegate(string value)
{ decIP += long.Parse(value) << (shift * 8); shift--; });

return decIP.ToString();
}



Here’s a bit of trivia on IP addresses and the internet: it’s all a lie.  You don’t actually “go” to a web site by name; that’s just what you type.  A web site end point is actually a port on an IP address.  Typically HTTP runs on port 80, so that’s assumed by the http prefix.  So, you can go to http://www.google.com, or you can go to http://209.85.171.100 and it’s the same thing.  What’s cool is that if you take that IP and convert it to decimal, such as http://3512052580, you can also go to that address and see the Google home page. Depending on your browser, it might convert that 3512052580 to the IP address for you, but it all goes to the same place.



Here’s how that code works:




  • Using the string.Split function and a character ‘.’ we break apart the list of octets from the IP address into a generic list of strings.  string.Split returns an array, which we can pass into the constructor of the List<T>.


  • Quickly, we create a variable to hold our result, then a counter to help us shift the bits.


  • Next, we ‘walk’ across the list using the ForEach method.  This method can accept a delegate to an existing function or an anonymous delegate in-line.


  • We tell the compiler that we want the in-line version by creating a code block {…} that accepts a string parameter called value.


  • Each octet is passed into the method, which, in turn, shifts the value 8 bits (times the number in our shift counter) and adds it to our result.  The first octet needs to be shifted 24 bits (3 bytes), the second 16 and the third 8.  The last octet does not need to be shifted (0 * 8 = 0) so it is evaluated to its decimal value and added to the result.



Easy peasy lemon squeezy.  And that’s how you use .Net – not just loops and old-school brute force – to convert an IP address to a decimal.



Hrm…actually…I guess I’m returning that as a string…

No comments:

Post a Comment