C# – Validate an IP address

Use IPAddress.Parse() to parse an IP address from a string. This handles both IPv4 and IPv6 addresses and throws an exception if the string can’t be parsed into a valid IP address. Here’s an example:

using System.Net;

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

IPAddress ipv6 = IPAddress.Parse("0:0:0:0:0:0:0:1");
Console.WriteLine($"Parsed IPv6: {ipv6}");
Code language: C# (cs)

This outputs the following:

Parsed IPv4: 192.168.0.10
Parsed IPv6: ::1Code language: plaintext (plaintext)

Use IPAddress.TryParse() if you don’t want exceptions to be thrown. It returns false if the string doesn’t represent a valid IP address. Here’s an example:

using System.Net;

var input = "192..12";

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

This outputs the following:

Invalid IP AddressCode language: plaintext (plaintext)

Validate string is IPv4 address in format x.x.x.x

If you’re handling input from a user, you’re most likely trying to validate an IPv4 address with a strict 3-dot format (i.e. 192.168.0.10). The problem is that IPAdress.Parse() is very flexible, and it can parse seemingly invalid IP addresses, such as the following scenarios:

  • It parses “1” into 0.0.0.1. It handles IPv4 addresses with 1 to 4 “parts” separated by dots, whereas you’re only interested in the 3-dot format.
  • It parses “127.0000000.0.1” into 127.0.0.1. It ignores the excess leading 0’s, whereas you probably want to validate the user input exactly as is without changing it.
  • It parses more than just IPv4 (such as IPv6).

Don’t worry, you don’t need to resort to using regex (or custom parsing). You can use IPAddress.TryParse(), check for AddressFamily.InterNetwork (IPv4), and compare IPAddress.ToString() with the input string. Here’s an example:

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 //it's IPv4
    && ip.ToString() == input; //it's in 3-dot format
}
Code language: C# (cs)

Note: IPAddress.ToString() outputs the IP address in the IPv4 proper 3-dot format. Hence, comparing with the input string tells you if the input is also in the expected format.

Leave a Comment