ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

IsValidIPAddress

Validates whether a string is a valid IPv4 address.

Source

public static bool IsValidIPAddress(this string s)
{
    return Regex.IsMatch(s, 
            @"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b");
}

Example

//returns false
string s = "192.168.1.256";
bool b = s.IsValidIPAddress();
//returns true
string s = "192.168.1.254";
bool b = s.IsValidIPAddress();

Author: Arjan Keene

Submitted on: 24 feb. 2008

Language: C#

Type: System.String

Views: 7787