In this post, I have used Regular expression to validate if the IP address provided as string is valid IP Address or not.
Usefull when we want user to input IP address in our application and we want to check if the IP address is corrct format or not.
public bool IsValidIP(string addr)
{
//create our match pattern
string strPattern = @”^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$”;
//create our Regular Expression object
Regex check = new Regex(strPattern);
//boolean variable to hold the status
bool valid = false;
//check to make sure an ip address was provided
if (addr == “”)
{
//no address provided so return false
valid = false;
}
else
{
//address provided so use the IsMatch Method
//of the Regular Expression object
valid = check.IsMatch(addr, 0);
}
//return the results
return valid;
}