两种方法:
一、用IPAddress.Parse(string)函数,然后捕获异常;
try
{
IPAddress ipTry = IPAddress.Parse(callAgentAddr);
}
catch
{
MessageBox.Show("请输入正确的IP地址:(0-255).(0-255).(0-255).(0-255)");
return;
}
二、使用正则表达式:
public bool IsValidIP(string ip)
{
if (System.Text.RegularExpressions.Regex.IsMatch(ip,"[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"))
{
string[] ips = ip.Split('.');
if (ips.Length == 4 || ips.Length == 6)
{
if(System.Int32.Parse(ips[0]) < 256 && System.Int32.Parse(ips[1]) < 256 & System.Int32.Parse(ips[2]) < 256 & System.Int32.Parse(ips[3]) < 256)
return true;
else
return false;
}
else
return false;
}
else
return false;
}
一、用IPAddress.Parse(string)函数,然后捕获异常;
try
{
IPAddress ipTry = IPAddress.Parse(callAgentAddr);
}
catch
{
MessageBox.Show("请输入正确的IP地址:(0-255).(0-255).(0-255).(0-255)");
return;
}
二、使用正则表达式:
public bool IsValidIP(string ip)
{
if (System.Text.RegularExpressions.Regex.IsMatch(ip,"[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"))
{
string[] ips = ip.Split('.');
if (ips.Length == 4 || ips.Length == 6)
{
if(System.Int32.Parse(ips[0]) < 256 && System.Int32.Parse(ips[1]) < 256 & System.Int32.Parse(ips[2]) < 256 & System.Int32.Parse(ips[3]) < 256)
return true;
else
return false;
}
else
return false;
}
else
return false;
}