I have found this method very useful for validating IP4 address. Pass in any IP address as parameter while calling this method will return you true on success and false on failure.

 

Code:

/// <summary>
/// Check IP Address, will accept 0.0.0.0 as a valid IP
/// </summary>
/// <param name="strIP">0.0.0.0 style IP address</param>
/// <returns>bool</returns>
public static Boolean CheckIPValid(String strIP)
{
// Split string by ".", check that array length is 3
char chrFullStop = '.';
string[] arrOctets = strIP.Split(chrFullStop);
if (arrOctets.Length != 4)
{
return false;
}
// Check each substring checking that the int value is less than 255
// and that is char[] length is !> 2
Int16 MAXVALUE = 255;
Int32 temp; // Parse returns Int32
foreach (String strOctet in arrOctets)
{
if (strOctet.Length > 3)
{
return false;
}
temp = int.Parse(strOctet);
if (temp > MAXVALUE)
{
return false;
}
}
return true;
}

This method is declared as static which may be declared something different, ie. simply as private or public scope.

Other articles of this category:

  • Changing font in C#

    FontStyle is an enumeration you can Or them together to add or Xor to remove. i.e. to...