VALIDATE MAC ADDRESS (REGEX)

I use devices all the time that have MAC addresses that need to be validated.

/// <summary>

/// Determines whether he specified macAddress is valid.

/// </summary>

/// <param name="macAddress">Mac Address.</param>

/// <returns>string MACAddress or null string if not valid</returns>

public static string IsValidMAC(string macAddress)

{

if (macAddress.StartsWith("/spa")) macAddress = macAddress.Substring(4);

macAddress = macAddress.Replace(":", "");

string result = "";

Regex rx = new Regex("([0-9a-fA-F][0-9a-fA-F]-){5}([0-9a-fA-F][0-9a-fA-F])", RegexOptions.IgnoreCase);

Match m = rx.Match(macAddress);

result = m.Groups[0].Value;

if (result.Length == 17)

{

return result;

}

else

{

rx = new Regex("([0-9a-fA-F][0-9a-fA-F]){5}([0-9a-fA-F][0-9a-fA-F])", RegexOptions.IgnoreCase);

Match m2 = rx.Match(macAddress);

result = m2.Groups[0].Value;

if (result.Length == 12)

{

return result;

}

return result;

}

}


Submission Date:  10/19/2005 11:02:53 AM
Submitted By:  Peter Bromberg
My Home Page:  http://www.eggheadcafe.com

By Peter Bromberg   Popularity  (434 Views)