How to validate an IP address in C#

By FoxLearn 12/24/2024 7:44:18 AM   25
In .NET, the System.Net.IPAddress class provides convenient methods for working with IP addresses, specifically Parse() and TryParse().

The IPAddress.Parse() method takes a string representation of an IP address and attempts to convert it into an IPAddress object. If the string represents a valid IP address, it returns an IPAddress instance. However, if the string cannot be parsed into a valid IP address (whether it's an invalid format or type), Parse() throws a FormatException.

For example:

using System.Net;

IPAddress ipv4 = IPAddress.Parse("192.168.0.11");
Console.WriteLine($"Parsed IPv4: {ipv4}");

IPAddress ipv6 = IPAddress.Parse("0:0:0:0:0:0:0:1");
Console.WriteLine($"Parsed IPv6: {ipv6}");

Output:

Parsed IPv4: 192.168.0.11
Parsed IPv6: ::1

As shown, Parse() successfully handles both IPv4 and IPv6 addresses. However, if you pass an invalid string (e.g., "192..12" or "Invalid IP"), the method will throw an exception.

To avoid exceptions and handle invalid input more gracefully, you can use IPAddress.TryParse().

using System.Net;

var input = "192..11"; // Invalid IP address

if (IPAddress.TryParse(input, out IPAddress ipv4))
{
    Console.WriteLine($"Valid IP: {ipv4}");
}
else
{
    Console.WriteLine("Invalid IP address");
}

Output:

Invalid IP address

In this example, the invalid string "192..11" is gracefully handled by TryParse(), which returns false and avoids throwing an exception.

In many cases, especially when handling user input, you may want to strictly validate IPv4 addresses in the common 3-dot format (e.g., "192.168.0.11") and reject malformed inputs, such as those with extra dots, leading zeros, or those representing an IPv6 address.

While IPAddress.Parse() is flexible, it can parse some IP addresses that may not match the expected format.

For example:

  • IPAddress.Parse("1") becomes 0.0.0.1.
  • IPAddress.Parse("127.0000000.0.1") becomes 127.0.0.1, ignoring extra zeros.
  • IPAddress.Parse("0:0:0:0:0:0:0:1") would parse as an IPv6 address, which might not be what you intend.

To strictly validate an IPv4 address in the 3-dot format, you can combine IPAddress.TryParse() with checks for the AddressFamily property and a comparison of the parsed IP address with the input string.

using System.Net;
using System.Net.Sockets;

Console.WriteLine(IsValidIPv4("192.168.0.10"));    // true
Console.WriteLine(IsValidIPv4("0"));                // false
Console.WriteLine(IsValidIPv4("192.0"));            // false
Console.WriteLine(IsValidIPv4("0:0:0:0:0:0:0:1")); // false
Console.WriteLine(IsValidIPv4("127.0000000.0.1"));  // false

bool IsValidIPv4(string input)
{
    return IPAddress.TryParse(input, out IPAddress ip)
        && ip.AddressFamily == AddressFamily.InterNetwork  // Ensure it's IPv4
        && ip.ToString() == input;                         // Check if the string matches the parsed format
}

Output:

true
false
false
false
false

The IPAddress.Parse() and IPAddress.TryParse() methods provide essential functionality when working with IP addresses in .NET applications. While Parse() is useful for guaranteed valid input, TryParse() offers a more forgiving approach when dealing with user input or external data sources.