Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Validate IP Address in C#
An IP Address is an Internet Protocol address that is a series of numbers assigned to each device on a computer network. In C#, the IPAddress class in the System.Net namespace provides methods to work with and validate IP addresses.
There are several approaches to validate IP addresses in C#, including using the built-in IPAddress.TryParse() method and regular expressions for custom validation.
Syntax
Following is the syntax for using IPAddress.TryParse() method −
bool IPAddress.TryParse(string ipString, out IPAddress address)
Parameters
ipString − A string that contains an IP address in dotted-decimal notation for IPv4 and in colon-hexadecimal notation for IPv6.
address − When this method returns, contains the
IPAddressequivalent of the IP address contained inipString, if the conversion succeeded, ornullif the conversion failed.
Return Value
Returns true if ipString was converted successfully; otherwise, false.
Using IPAddress.TryParse() Method
The IPAddress.TryParse() method is the most reliable way to validate IP addresses as it handles both IPv4 and IPv6 formats −
using System;
using System.Net;
namespace IPAddressDemo {
class Example {
public static void Main() {
string[] testAddresses = {
"192.168.1.1",
"256.300.400.500",
"10.0.0.1",
"2001:0db8:85a3:0000:0000:8a2e:0370:7334",
"invalid.ip.address"
};
foreach (string ipAddr in testAddresses) {
IPAddress IP;
bool isValid = IPAddress.TryParse(ipAddr, out IP);
if (isValid) {
Console.WriteLine("{0} is a valid IP address (Type: {1})", ipAddr, IP.AddressFamily);
} else {
Console.WriteLine("{0} is not a valid IP address", ipAddr);
}
}
}
}
}
The output of the above code is −
192.168.1.1 is a valid IP address (Type: InterNetwork) 256.300.400.500 is not a valid IP address 10.0.0.1 is a valid IP address (Type: InterNetwork) 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is a valid IP address (Type: InterNetworkV6) invalid.ip.address is not a valid IP address
Using Regular Expressions for IPv4 Validation
For more specific IPv4 validation requirements, you can use regular expressions −
using System;
using System.Text.RegularExpressions;
namespace IPAddressDemo {
class RegexValidator {
public static bool IsValidIPv4(string ip) {
string pattern = @"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
return Regex.IsMatch(ip, pattern);
}
public static void Main() {
string[] testIPs = {
"192.168.1.1",
"255.255.255.255",
"256.1.1.1",
"192.168.01.1",
"192.168.1"
};
foreach (string ip in testIPs) {
bool isValid = IsValidIPv4(ip);
Console.WriteLine("{0} is {1}valid IPv4 address", ip, isValid ? "" : "not ");
}
}
}
}
The output of the above code is −
192.168.1.1 is valid IPv4 address 255.255.255.255 is valid IPv4 address 256.1.1.1 is not valid IPv4 address 192.168.01.1 is not valid IPv4 address 192.168.1 is not valid IPv4 address
Comprehensive IP Validation with Custom Method
Here's a comprehensive approach that combines both methods and provides detailed validation information −
using System;
using System.Net;
using System.Net.Sockets;
namespace IPAddressDemo {
class ComprehensiveValidator {
public static string ValidateIP(string ipString) {
if (string.IsNullOrWhiteSpace(ipString)) {
return "Empty or null input";
}
IPAddress address;
if (IPAddress.TryParse(ipString, out address)) {
if (address.AddressFamily == AddressFamily.InterNetwork) {
return "Valid IPv4 address";
} else if (address.AddressFamily == AddressFamily.InterNetworkV6) {
return "Valid IPv6 address";
} else {
return "Valid IP address (Unknown type)";
}
} else {
return "Invalid IP address format";
}
}
public static void Main() {
string[] testCases = {
"192.168.1.1",
"::1",
"fe80::1",
"300.300.300.300",
"192.168.1",
"",
"192.168.1.1.1"
};
Console.WriteLine("IP Address Validation Results:");
Console.WriteLine("================================");
foreach (string testIP in testCases) {
string result = ValidateIP(testIP);
Console.WriteLine("'{0}' -> {1}", testIP, result);
}
}
}
}
The output of the above code is −
IP Address Validation Results: ================================ '192.168.1.1' -> Valid IPv4 address '::1' -> Valid IPv6 address 'fe80::1' -> Valid IPv6 address '300.300.300.300' -> Invalid IP address format '192.168.1' -> Invalid IP address format '' -> Empty or null input '192.168.1.1.1' -> Invalid IP address format
Comparison of Validation Methods
| Method | IPv4 Support | IPv6 Support | Performance | Flexibility |
|---|---|---|---|---|
| IPAddress.TryParse() | Yes | Yes | High | Standard validation |
| Regular Expressions | Yes | Complex | Medium | Custom rules possible |
| Custom parsing | Yes | Yes | Low | Full control |
Conclusion
The IPAddress.TryParse() method is the recommended approach for validating IP addresses in C# as it handles both IPv4 and IPv6 formats reliably. For specific validation requirements, regular expressions can provide additional control over the validation process.
