我有一个方法来验证参数 IP 地址。作为一个整体开发的新手,我想知道是否有更好的方法来做到这一点。
/// <summary>
/// Check IP Address, will accept 0.0.0.0 as a valid IP
/// </summary>
/// <param name="strIP"></param>
/// <returns></returns>
public bool 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;
}
它很简单(我可以做到)但它似乎可以解决问题。
最佳答案
IPAddress.TryParse
的限制方法是它验证一个字符串是否可以转换为 IP 地址,因此如果它提供了一个像 "5"
这样的字符串值,它会认为它是 "0.0.0.5"
。
另一种验证 IPv4 的方法如下:
public bool ValidateIPv4(string ipString)
{
if (String.IsNullOrWhiteSpace(ipString))
{
return false;
}
string[] splitValues = ipString.Split('.');
if (splitValues.Length != 4)
{
return false;
}
byte tempForParsing;
return splitValues.All(r => byte.TryParse(r, out tempForParsing));
}
可以这样测试:
List<string> ipAddresses = new List<string>
{
"2",
"1.2.3",
"1.2.3.4",
"255.256.267.300",
"127.0.0.1",
};
foreach (var ip in ipAddresses)
{
Console.WriteLine($"{ip} ==> {ValidateIPv4(ip)}");
}
输出将是:
2 ==> False
1.2.3 ==> False
1.2.3.4 ==> True
255.256.267.300 ==> False
127.0.0.1 ==> True
您也可以使用 IPAddress.TryParse
,但它有局限性并且可能导致解析不正确。
System.Net.IPAddress.TryParse Method
Note that TryParse returns true if it parsed the input successfully, but that this does not necessarily mean that the resulting IP address is a valid one. Do not use this method to validate IP addresses.
但这适用于至少包含三个点的普通字符串。像这样的东西:
string addrString = "192.168.0.1";
IPAddress address;
if (IPAddress.TryParse(addrString, out address)) {
//Valid IP, with address containing the IP
} else {
//Invalid IP
}
使用 IPAddress.TryParse
,您可以检查三个点是否存在,然后调用 TryParse
,例如:
public static bool ValidateIPv4(string ipString)
{
if (ipString.Count(c => c == '.') != 3) return false;
IPAddress address;
return IPAddress.TryParse(ipString, out address);
}
关于c# - 验证 IP 地址的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11412956/