using System;
namespace Sp.Common
{
public class ValidatorHelper
{
/// <summary>
/// 验证IPv4地址
/// [第一位和最后一位数字不能是0或255;允许用0补位]
/// </summary>
/// <param name="input">待验证的字符串</param>
/// <returns>是否匹配</returns>
public static bool IsIPv4(string input)
{
//string pattern = @"^(25[0-4]|2[0-4]d]|[01]?d{2}|[1-9]).(25[0-5]|2[0-4]d]|[01]?d?d).(25[0-5]|2[0-4]d]|[01]?d?d).(25[0-4]|2[0-4]d]|[01]?d{2}|[1-9])$";
//return IsMatch(input, pattern);
string[] IPs = input.Split('.');
if (IPs.Length != 4)
return false;
int n = -1;
for (int i = 0; i < IPs.Length; i++)
{
if (i == 0 || i == 3)
{
if (int.TryParse(IPs[i], out n) && n > 0 && n < 255)
continue;
else
return false;
}
else
{
if (int.TryParse(IPs[i], out n) && n >= 0 && n <= 255)
continue;
else
return false;
}
}
return true;
}
}
}