Click here to Skip to main content
12,072,809 members (71,664 online)
Click here to Skip to main content
Add your own
alternative version


8 bookmarked

Extending the IPAddress object to allow relative comparisons of two IP addresses

, 1 Jun 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
This article outlines how to extend the IPAddress object to provide additional functionality for relative numeric comparisons of two IP addresses.


It is occasionally necessary to determine the relative position of two IP addresses or if a particular IP address falls within a particular range. In the 1.0 and 1.1 frameworks, the IPAddress object had an 'Address' property. This returned a long value as a representation of an IP address, and allowed simple numeric comparison of IP addresses to determine their relative values.

In the 2.0 framework, the Address property is deprecated. This may be due to the advent of support for IPv6 addressing. IPv4 addresses can be represented with 32 bits of data, and therefore can be represented as a long. IPv6 addresses are made up of 128 bits of data, and this poses a problem if trying to be represented as a long value.

In the 2.0 framework, the IPAddress object has an Equal() method to determine if two IPAddress objects are the same, but there is no inbuilt method to determine the relative position of two addresses that are not equal. In looking for existing solutions available, the only ones that I could find used text comparisons to determine the relative values of two IP addresses. I've created a solution that doesn't use text comparisons, by using existing methods and extending the existing IPAddress object.


The IPAddress object can be inherited to extend the functionality. This article looks at a basic method to add functionality to the base object to determine the relative position of two addresses and to determine if an address is within a given range. These functions will support both IPv4 and IPv6.

Key Concept

The 2.0 framework IPAddress object has a method called GetAddressBytes() which returns a byte array representation of the stored address. For IPv4, this byte array has a length = 4; for IPv6, the array length = 16. Given two addresses, by comparing the relative value of each pair of bytes, it is trivial to determine the relative position of the two IP addresses.

Comparing two addresses from different address families is not supported. It is impossible to determine if an IPv4 address is higher or lower than an IPv6 address.


The derived object will be called ComparibleIPAddress. It should inherit from System.Net.IPAddress.


You must specify a constructor for the inherited object. All the constructor must do is call the constructor of the base object. This is necessary as, in this case, the base object doesn't have a parameter-less constructor.

For consistency, I have included a constructor to mirror each of the available constructors in the base object.

public ComparibleIPAddress(byte[] address)
    : base(address)
    // must override this constructor to enable build //    

public ComparibleIPAddress(Int64 address)
    : base(address)
    // must override this constructor to enable
    // build / compatibility with base class constructors

public ComparibleIPAddress(byte[] address, Int64 scopeid)
    : base(address, scopeid)
    // must override this constructor to enable
    // build / compatibility with base class constructors

CompareTo Function

The purpose of this function is to allow us to compare the current IP address to a given value and determine their relative positions. If the current IP address and the passed address are not in the same address family, the function throws an ArgumentOutOfRangeException.

Each address is converted to a byte array.

Each pair in the two byte arrays are compared with each other. If they are not equal, their relative values are determined and processing is completed.

public int CompareTo(ComparibleIPAddress value)
    int returnVal = 0;
    if (this.AddressFamily == value.AddressFamily)
        byte[] b1 = this.GetAddressBytes();
        byte[] b2 = value.GetAddressBytes();

        for (int i = 0; i < b1.Length; i++)
            if (b1[i] < b2[i])
                returnVal = -1;
            else if (b1[i] > b2[i])
                returnVal = 1;
        throw new ArgumentOutOfRangeException("value", 
              "Cannot compare two addresses no in the same Address Family.");

    return returnVal;

IsInRange Function

This is an extension of the CompareTo function. Once we are able to determine the relative position of two addresses, it is trivial to determine if a given addresses is within a range of addresses.

This function checks that all addresses are within the same address families. Again, an ArgumentOutOfRangeException is thrown if they are not.

public bool IsInRange(ComparibleIPAddress rangeStartAddress, 
                      ComparibleIPAddress rangeEndAddress)
    bool returnVal = false;
    // ensure that all addresses are of the same type otherwise reject //
    if (rangeStartAddress.AddressFamily != rangeEndAddress.AddressFamily)
        throw new ArgumentOutOfRangeException("rangeStartAddress",
        String.Format("The Start Range type {0} and End Range type {1}" + 
                      " are not compatible ip address families.", 

    if (rangeStartAddress.AddressFamily == this.AddressFamily)
        returnVal = (CompareTo(rangeStartAddress) >= 0 
                       && CompareTo(rangeEndAddress) <= 0);   
        // no need to check for -2 value as this
        // check has already been undertaken to get into this block //
        throw new ArgumentOutOfRangeException("rangeStartAddress", 
            String.Format("The range type {0} and current value type {1}" + 
                          " are not compatible ip address families", 

    return returnVal;



A derived class can easily be created to provide additional functions for IP addresses.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

New Zealand New Zealand
Jayden has a background in Sofware Development particularly in the Health Sector in New Zealand. He currently manages an Information Management department for a Health Services Management company in Wellington, New Zealand.

You may also be interested in...

Comments and Discussions

SuggestionAdd operator overload - sample code Pin
Vincent DUVERNET (Nolmë Informatique)28-Jul-15 21:39
memberVincent DUVERNET (Nolmë Informatique)28-Jul-15 21:39 
SuggestionString Constructor for Derived ComparableIPAddress Class Pin
wesleymusgrove2-Jan-13 6:25
memberwesleymusgrove2-Jan-13 6:25 
SuggestionString Constructor for Derived ComparableIPAddress Class Pin
wesleymusgrove2-Jan-13 6:24
memberwesleymusgrove2-Jan-13 6:24 
GeneralRe: String Constructor for Derived ComparableIPAddress Class Pin
Andy_Zhang5-Mar-13 22:45
memberAndy_Zhang5-Mar-13 22:45 
QuestionTo handle comparing null vs. IPv4 vs. IPv6 Pin
JesseChisholm5-Jun-12 7:20
memberJesseChisholm5-Jun-12 7:20 
GeneralLooks great, small question Pin
Mark de Haan14-Nov-08 2:17
memberMark de Haan14-Nov-08 2:17 
GeneralRe: Looks great, small question Pin
jaydenm17-Nov-08 18:04
memberjaydenm17-Nov-08 18:04 
GeneralExtension Methods Pin
Ami Bar1-Jun-08 5:20
memberAmi Bar1-Jun-08 5:20 
GeneralRe: Extension Methods Pin
PIEBALDconsult1-Jun-08 6:03
memberPIEBALDconsult1-Jun-08 6:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160208.1 | Last Updated 1 Jun 2008
Article Copyright 2008 by jaydenm
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid