IP Address Math¶
Too frequently the existing implementation of the C#
IPAddress object is too limited for anything beyond some of the most trivial interactions. Mathematical operations in fact are wholly absent, forcing developers to directly manipulate bytes 1, often requiring a great deal of manual implementation of non-existent byte math. Don’t worry though, Arcus is here to fill in some of those gaps.
Unless otherwise specified regarding the math of the
IPAddress object treats it as an unsigned integer based on its bytes interpenetrated as 32-bit for IPv4 and 128-bit for IPv6 all in big-endian byte order.
IPAddress allows for the the addition or subtraction of a provided optional
long delta value.
There exist two implementations of Increment methods.
Increment and the safe
public static IPAddress Increment(this IPAddress input, long delta = 1)
public static bool TryIncrement(IPAddress input, out IPAddress address, long delta = 1)
Compare to Another IPAddress¶
IPAddress does not implement the standard comparison operators, and thus far we can’t write extension methods for operators on a class 2. Arcus did the next best thing, deciding not to extend the
IPAddress, opting to provide a handful of simple extension methods to bend the will of the
IPAddress to suit our needs.
Barring the use of the methods below, the DefaultIPAddressComparer may also be of interest to you.
It should be pretty obvious based on name alone as to what each of the following five methods will accomplish:
public static bool IsEqualTo(this IPAddress left, IPAddress right)
public static bool IsGreaterThan(this IPAddress left, IPAddress right)
public static bool IsGreaterThanOrEqualTo(this IPAddress left, IPAddress right)
public static bool IsLessThan(this IPAddress left, IPAddress right)
public static bool IsLessThanOrEqualTo(this IPAddress left, IPAddress right)
Slightly different than the other comparison extension method above is the IsBetween method. As is hopefully is obvious it will test if an
IPAddress occurs numerically between the given
low addresses. Likewise the inclusive bit may be set to include equality to either
high to be considered an inclusive between.
public static bool IsBetween(this IPAddress input, IPAddress low, IPAddress high, bool inclusive = true)
Get Min / Max¶
Max methods will return the
IPAddress left or
IPAddress right that is the smallest or largest of the two respectively.
public static IPAddress Min(IPAddress left, IPAddress right)
public static IPAddress Max(IPAddress left, IPAddress right)
IsAtMax tests the
IPAddress address to determine if it is at its minimum or maximum value respectively.
For IPv4 the minimum value is
0.0.0.0 (\(0\)), and maximum is
For IPv6 the minimum value is
:: (\(0\)), and maximum is
public static bool IsAtMin(this IPAddress address)
public static bool IsAtMax(this IPAddress address)