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.

Download  Run Code

 
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.

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.

Download  Run Code

That’s all about validating IPAddress in C#.