Peter Petrov’s Weblog

var me = from practice in programming where practice.IsBestPractice && practice.UseLambda select practice.OptimalPerformance;

Useful method – 3 of N – Validate IP address June 18, 2008

Filed under: C# — ppetrov @ 7:20 pm
Tags:

If you need to know if a string is a valid IP address this utility methods can help you

public static bool IsValidIPAddress(string address)
{
return IsValidIPAddress(address, IPVersion.V4);
}

public static bool IsValidIPAddress(string address, IPVersion version)
{
bool isValid = false;

if (!string.IsNullOrEmpty(address))
{
if (address.Length <= ((int)version * 3) + 3) { var parts = address.Split('.'); if (parts.Length == (int)version) { isValid = true; int index = 0; while (isValid && index < parts.Length) { byte partValue; isValid &= byte.TryParse(parts[index++], out partValue); } } } } return isValid; } [/sourcecode]where IPVersion is the following enum [sourcecode="csharp"] public enum IPVersion { V4 = 4, V6 = 6 } [/sourcecode]

Advertisements
 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s