C# – IPv4 range validation

Given a starting IPv4 address and an ending IPv4 address, how do you know if this is a valid range?

The range is valid if:

  • The starting IPv4 address is valid.
  • The ending IPv4 address is valid.
  • The range is a class C network with subnet mask This means the starting IP and ending IP share the first three octets. Note: This was my requirement when I had to solve this. If your range is a class B or A, adjust the code accordingly.
  • The starting IPv4 address comes before the ending IPv4 address.

For example:

Given startingIP= Given endingIP= startingIP is valid and endingIP is valid and startingIP first 3 octets (127.0.0) == endingIP first 3 octets (127.0.0) and startingIP last octet (1) < endingIP last octet (10)
Code language: plaintext (plaintext)

This article will show the code that implements this validation logic.

IPv4 range validation code and tests

For the first two conditions – are the starting and ending IP addresses valid IPv4 addresses – we’ll use the built-in System.Net.IPAddress.TryParse().

For the last two conditions, we’ll be comparing the octets (an IPv4 address is expressed in dotted decimal notation, i.e., where each dot separates an octet.). To check if the starting and ending IP addresses are in the same class C network (subnet, we’ll compare the first three octets. Then we’ll make sure the starting IP comes before the ending IP by comparing the fourth octet.

using System.Net; public static class IPv4Util { public static bool IsRangeValid(string ipRangeStart, string ipRangeEnd) { if (!TryParseIPv4(ipRangeStart, out IPAddress start) || !TryParseIPv4(ipRangeEnd, out IPAddress end)) { return false; } byte[] startBytes = start.GetAddressBytes(); byte[] endBytes = end.GetAddressBytes(); return startBytes[0] == endBytes[0] && startBytes[1] == endBytes[1] && startBytes[2] == endBytes[2] && startBytes[3] < endBytes[3]; } private static bool TryParseIPv4(string ipString, out IPAddress ipAddress) { return IPAddress.TryParse(ipString, out ipAddress) && ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork; } }
Code language: C# (cs)

The following parameterized unit test proves the validation logic by testing five test cases.

[DataRow("", "", false)] [DataRow("127.0.0.", "", false)] [DataRow("", "", false)] [DataRow("", "", false)] [DataRow("", "", true)] [DataTestMethod()] public void IsRangeValidTest(string ipRangeStart, string ipRangeEnd, bool shouldBeValid) { //arrange and act var isValid = IPv4Util.IsRangeValid(ipRangeStart, ipRangeEnd); //assert Assert.AreEqual(shouldBeValid, isValid); }
Code language: C# (cs)

Leave a Comment