Validate IPAddress in C#
This post will discuss how to validate IPAddress in C#.
1. Using IPAddress.TryParse() method
You can use the IPAddress.TryParse() method to determine whether a string is a valid IP address. It returns true if the input string can be successfully parsed as an IP address; otherwise false.
Note that this method can return true even if the string does not represent a valid IP address. For example, this method will consider the input string "1" as "0.0.0.5" and returns true. So, it is recommended to invoke this method on IP addresses in dotted-decimal format. i.e. contains three dots for IPv4.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Net; public class Example { public static bool ValidateIPv4(string ip) { IPAddress address; return ip != null && ip.Count(c => c == '.') == 3 && IPAddress.TryParse(ip, out address); } public static void Main() { string ip = "127.0.0.1"; if (ValidateIPv4(ip)) { Console.WriteLine("Valid IP"); } else { Console.WriteLine("Invalid IP"); } } } |
The IPAddress.TryParse() method takes an out parameter, which stores the IPAddress if the parsing is a success. The code can be shortened as follows in case the out parameter is not required.
|
1 2 3 4 5 |
public static bool ValidateIPv4(string ip) { return ip != null && ip.Count(c => c == '.') == 3 && IPAddress.TryParse(ip, out _); } |
2. Using Custom Routine
Another approach to validate an IPv4 address is to split the input on dots and check the resultant string array’s length. Then, simply validate if each chunk has a Byte equivalent or not using the Byte.TryParse() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System; public class Example { public static bool ValidateIPv4(string ip) { if (String.IsNullOrEmpty(ip)) { return false; } string[] nums = ip.Split('.'); return nums.Length == 4 && nums.All(x => byte.TryParse(x, out _)); } public static void Main() { string ip = "127.0.0.1"; if (ValidateIPv4(ip)) { Console.WriteLine("Valid IP"); } else { Console.WriteLine("Invalid IP"); } } } |
That’s all about validating IPAddress in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)