AddressParser


The AddressParser class provides 2 static methods. The ParseIpAddress method returns true if the format of an IP address in the form w.x.y.z is valid. Otherwise an exception is thrown. The ParseMacAddress method returns true if a MAC address in the form uu:vv:ww:xx:yy:zz is valid. Otherwise an exception is thrown.

public class AddressParser
{
public static bool ParseIpAddress(string addr)
{
string[] elements = addr.Split(new Char[] {'.'});
// make sure there are 4 numeric elements of the IP address
if (elements.Length==4)
{
if( inRange(elements, 10) )
return true;
}
else // does not have 4 elements
{
if (addr.Length == 0)
throw new Exception("Need to enter an IP address");
else
throw new Exception("Not a valid IP address");
}
return true;
}
public static bool ParseMacAddress(string addr)
{
string[] elements = addr.Split(new Char[] {':'});
// make sure there are 4 numeric elements of the IP address
if (elements.Length==6)
{
if( AddressParser.inRange(elements, 16) )
return true;
}
else // does not have 6 elements
{
if (addr.Length == 0)
throw new Exception("Need to enter a MAC address");
else
throw new Exception("Not a valid MAC address");
}
return true;
}
// Convert.ToInt32(s, bas), where base = [10,16]
// IP address: base 10
// MAC address: base 16
// verifies each element is >= 0 and <= 255
protected static bool inRange(string[] a, int bas)
{
int n = 0;
foreach ( string s in a )
{
try
{
n = Convert.ToInt32(s, bas);
if( n < 0 || n > 255 )
{
throw new Exception("Address element not in range");
}
}
// catch non-numeric ip addr element exceptions
catch
{
throw new Exception("Address element '" + s + "' not in range");
}
}
return true;
}
}


Similar Articles