IP地址验证 [英] IP address validation
问题描述
I'm refactoring my code and wanted to use the IPAddress.TryParse
method to validate if a string is a valid IPv4 address instead of using regular expressions:
public static bool IsIPv4(string value)
{
IPAddress address;
if (IPAddress.TryParse(value, out address))
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
return true;
}
}
return false;
}
我的单元测试现在失败,因为这些输入值返回true
并被解析为以下IPAddress
对象:
My unit test is now failing because these input values return true
and get parsed to the following IPAddress
objects:
value = "0.0.0.0" -> address = {0.0.0.0}
value = "255.255.255" -> address = {255.255.0.255}
value = "65536" -> address = {0.1.0.0}
这有意义吗?我可以看到 0.0.0.0
从技术上讲是有效的IPv4地址,即使用户输入该地址毫无意义.那另外两个呢?为什么要按原样转换它们,即使对用户来说可能不是透明的,我也应该将它们视为有效,也许只是忘记输入句点(65536
而不是6.5.5.36
).
Does this make sense? I can see that 0.0.0.0
is technically a valid IPv4 address, even if it makes no sense for the user to enter that. What about the other two? Why are they converted in the way they are and should I treat them as valid even if it might not be transparent for the user, who maybe just forgot to enter the periods (65536
instead of 6.5.5.36
).
我们非常感谢您的帮助.
Any help is most appreciated.
推荐答案
它看起来像一些代码供您参考:
// verify that IP consists of 4 parts
if (value.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries).Length == 4)
{
IPAddress ipAddr;
if (IPAddress.TryParse(value, out ipAddr))
{
// IP is valid
}
else
// invalid IP
}
else
// invalid IP
这篇关于IP地址验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!