gpt4 book ai didi

c# - IPAddress.TryParse 返回不需要的结果

转载 作者:太空宇宙 更新时间:2023-11-03 17:40:55 24 4
gpt4 key购买 nike

我有一个函数,它使用 IPAddress 类返回给定 IP 地址是否有效。我正在测试它,即使我在没有点作为参数的情况下传递“0123456”或“11111”或“99999”,它也会返回有效(真)。我用 VB.net 和 C# 编写了它,结果相同。

// C#
public bool CheckIpAddress(string ipAddr)
{
IPAddress ip = null;
return IPAddress.TryParse(ipAddr,out ip);
}

// VB.net
Public Function CheckIpAddress(ipAddr As String) As Boolean
Dim ip As IPAddress = Nothing

Return Net.IPAddress.TryParse(ipAddr, ip)
End Function

有人能解释一下为什么会这样吗?我已经通过互联网将我的代码与一些资源进行了匹配,没有问题。

最佳答案

IP 地址只是 32 位数字,所以 11111 绝对是一个正确的 IP 地址。 IP 地址中的点只是为了让人们更容易阅读它们。它们不是必需的。

IP addresses are binary numbers, but they are usually stored in text files and displayed in human-readable notations, such as 172.16.254.1 (for IPv4), and 2001:db8:0:1234:0:567:8:1 (for IPv6).

from IP address - Wikipedia

这就是 IPAddress.TryParse 返回 true 的原因。

它甚至在 MSDN 上有描述:IPAddress.Parse Method

The number of parts (each part is separated by a period) in ipString determines how the IP address is constructed. A one part address is stored directly in the network address. A two part address, convenient for specifying a class A address, puts the leading part in the first byte and the trailing part in the right-most three bytes of the network address. A three part address, convenient for specifying a class B address, puts the first part in the first byte, the second part in the second byte, and the final part in the right-most two bytes of the network address.

还有一个例子(见第一个):

1 -- "65536"       0.0.255.255
2 -- "20.2" 20.0.0.2
2 -- "20.65535" 20.0.255.255
3 -- "128.1.2" 128.1.0.2

关于c# - IPAddress.TryParse 返回不需要的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23193921/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com