IP Address Comparison and Conversion in C#

When using .NET and C#, IP Address information is stored in the System.Net.IPAddress class. The System.Net.IPAddress class provides no method for comparing IP addresses except for equality (==). There is no greater than or less then comparison operator available. In addition, the IPAddress class has a deprecated field "Address" which returns a long representation of the IP address. Because this function has been deprecated, I'll reimplement it here just for the sake of it.

This article provides examples for comparing IP addresses, converting to System.Net.IPAddress objects, and converting to uint representations so that comparisons can be performed.

Overview

This class provides functions for converting and comparing IP addresses. Something that is missing from the System.Net.IPAddress class. This class stands alone and therefore does not derive (as it could) from the System.Net.IPAddress class, nor does it implement any operator overloading. This prevents the need to actually instantiate classes for these simple operations.

This code is provided free for modification without warrantee, so please refactor it as you need. The purpose of this class is for example/educational purposes.

Code

The class for performing IP conversion and comparison functions is self contained and is self describing. Any ambiguity is documented as comments in the source.

using System;
using System.Net;

namespace LoweSoftware.Tools
{
   /// <summary>
   /// Used to convert and compare IP addresses.
   /// 
   /// By Alexander Lowe, Lowe*Software.
   /// http://www.lowesoftware.com
   /// 
   /// Free for use and modification. No warranty express or
   /// implied.
   /// </summary>
   class IPCompare
   {
      /// <summary>
      /// Compares two IP addresses for equality. 
      /// </summary>
      /// <param name="IPAddr1">The first IP to compare</param>
      /// <param name="IPAddr2">The second IP to compare</param>
      /// <returns>True if equal, false if not.</returns>
      static public bool AreEqual(string IPAddr1, string IPAddr2)
      {
         // convert to long in case there is any zero padding in
         // the strings
         return IPAddressToLongBackwards(IPAddr1)==
            sIPAddressToLongBackwards(IPAddr2);
      }

      /// <summary>
      /// Compares two string representations of an Ip address to
      /// see if one is greater than the other
      /// </summary>
      /// <param name="ToCompare">The IP address on the left hand
      /// side of the greater than operator</param>
      /// <param name="CompareAgainst">The Ip address on the right
      /// hand side of the greater than operator</param>
      /// <returns>True if ToCompare is greater than CompareAgainst,
      /// else false</returns>
      static public bool IsGreater(string ToCompare,
                                   string CompareAgainst)
      {
         // convert to long in case there is any zero padding in
         // the strings
         return IPAddressToLongBackwards(ToCompare)>
            IPAddressToLongBackwards(CompareAgainst);
      }

      /// <summary>
      /// Compares two string representations of an Ip address to
      /// see if one is less than the other
      /// </summary>
      /// <param name="ToCompare">The IP address on the left hand
      /// side of the less than operator</param>
      /// <param name="CompareAgainst">The Ip address on the right
      /// hand side of the less than operator</param>
      /// <returns>True if ToCompare is greater than CompareAgainst,
      /// else false</returns>
      static public bool IsLess(string ToCompare,
                                string CompareAgainst)
      {
         // convert to long in case there is any zero padding in
         // the strings
         return IPAddressToLongBackwards(ToCompare)<
            IPAddressToLongBackwards(CompareAgainst);
      }


      /// <summary>
      /// Compares two string representations of an Ip address to
      /// see if one is greater than or equal to the other.
      /// </summary>
      /// <param name="ToCompare">The IP address on the left hand
      /// side of the greater than or equal operator</param>
      /// <param name="CompareAgainst">The Ip address on the right
      /// hand side of the greater than or equal operator</param>
      /// <returns>True if ToCompare is greater than or equal to
      /// CompareAgainst, else false</returns>
      static public bool IsGreaterOrEqual(string ToCompare,
                                          string CompareAgainst)
      {
         // convert to long in case there is any zero padding in
         // the strings
         return IPAddressToLongBackwards(ToCompare)>
            =IPAddressToLongBackwards(CompareAgainst);
      }

      /// <summary>
      /// Compares two string representations of an Ip address to
      /// see if one is less than or equal to the other.
      /// </summary>
      /// <param name="ToCompare">The IP address on the left hand
      /// side of the less than or equal operator</param>
      /// <param name="CompareAgainst">The Ip address on the right
      /// hand side of the less than or equal operator</param>
      /// <returns>True if ToCompare is greater than or equal to
      /// CompareAgainst, else false</returns>
      static public bool IsLessOrEqual(string ToCompare,
                                       string CompareAgainst)
      {
         // convert to long in case there is any zero padding in
          the strings
         return IPAddressToLongBackwards(ToCompare)<
            =IPAddressToLongBackwards(CompareAgainst);
      }



      /// <summary>
      /// Converts a uint representation of an Ip address to a
      /// string.
      /// </summary>
      /// <param name="IPAddr">The IP address to convert</param>
      /// <returns>A string representation of the IP address.</returns>
      static public string LongToIPAddress(uint IPAddr)
      {
         return new System.Net.IPAddress(IPAddr).ToString();
      }

      /// <summary>
      /// Converts a string representation of an IP address to a
      /// uint. This encoding is proper and can be used with other
      /// networking functions such
      /// as the System.Net.IPAddress class.
      /// </summary>
      /// <param name="IPAddr">The Ip address to convert.</param>
      /// <returns>Returns a uint representation of the IP
      /// address.</returns>
      static public uint IPAddressToLong(string IPAddr)
      {
         System.Net.IPAddress oIP=System.Net.IPAddress.Parse(IPAddr);
         byte[] byteIP=oIP.GetAddressBytes();


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

         return ip;
      }


      /// <summary>
      /// This encodes the string representation of an IP address
      /// to a uint, but backwards so that it can be used to
      /// compare addresses. This function is used internally
      /// for comparison and is not valid for valid encoding of
      /// IP address information.
      /// </summary>
      /// <param name="IPAddr">A string representation of the IP
      /// address to convert</param>
      /// <returns>Returns a backwards uint representation of the
      /// string.</returns>
      static private uint IPAddressToLongBackwards(string IPAddr)
      {
         System.Net.IPAddress oIP=System.Net.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;
      }
   }
}

References

System.Net.IPAddress Class Reference, MSDN



About the Author

Alexander Lowe

Lowe*Software is a resource for software development with business needs in mind. The site is geared at entreprenurial software developers and managers looking to improve the quality of their software. On the site find open source projects, insightful articles, and other resources for advancing software development.

Downloads

Comments

  • Facts, moralistic a assess

    Posted by Dyncintognoxy on 01/20/2013 06:09am

    We [url=http://www.onlinebaccarat.gd]casino online[/url] be subjected to a corpulent library of absolutely unconditional casino games for you to monkey tricks right here in your browser. Whether you appetite to unaccustomed a provisions game master plan or honest sample manifest a occasional original slots in the presence of playing in the direction of real money, we have you covered. These are the exact uniform games that you can with at real online casinos and you can join in them all for free.

    Reply
  • fails with IP6 addresses!

    Posted by ghbyrkit on 10/16/2005 09:06am

    Possibly the reason Microsoft deprecated the conversion to long is that it fails with IP6 addresses. If that's so, then you needed to use a longlong in your article, not a long. Unfortunately, you don't mention this restriction (fails on IP6 addresses) in your article, despite claiming that the code/article is 'self documenting'.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Hybrid cloud platforms need to think in terms of sweet spots when it comes to application platform interface (API) integration. Cloud Velocity has taken a unique approach to tight integration with the API sweet spot; enough to support the agility of physical and virtual apps, including multi-tier environments and databases, while reducing capital and operating costs. Read this case study to learn how a global-level Fortune 1000 company was able to deploy an entire 6+ TB Oracle eCommerce stack in Amazon Web …

  • Event Date: April 15, 2014 The ability to effectively set sales goals, assign quotas and territories, bring new people on board and quickly make adjustments to the sales force is often crucial to success--and to the field experience! But for sales operations leaders, managing the administrative processes, systems, data and various departments to get it all right can often be difficult, inefficient and manually intensive. Register for this webinar and learn how you can: Align sales goals, quotas and …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds