将部分IP地址字符串转换为IP地址对象 [英] Converting a partial IP address string to an IP address object

查看:176
本文介绍了将部分IP地址字符串转换为IP地址对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 System.Net.IpAddress 允许将以下字符串转换为有效的IP地址?

Why does the System.Net.IpAddress allow the following strings to be converted to valid IP addresses?

 $b = [ipaddress]"10.10.10"
 $b.IPAddressToString
 #10.10.0.10

 $c = [ipaddress]"10.10"
 $c.IPAddressToString
 #10.0.0.10

 $d = [ipaddress]"10"
 $d.IPAddressToString
 #0.0.0.10

我可以看到模式是字符串中的最后一个八位字节是最后一个八位字节在 IPAddress 对象中,以及字符串中的第一个八位字节,用作 IPAddress ,并且零用于填充中间未指定的八位字节,如果有的话。

I can see that the pattern is that the last octet in the string is the last octet in the IPAddress object, and whatever the first octets are in the string, are used as the left most octets in the IPAddress, and zeros are used to fill the middle unspecified octets, if any.

但为什么会这样做?作为用户,我希望它在转换期间失败,除非指定了所有八位字节。
由于它允许这些转换,因此在检查字符串是否为有效IP地址时可能会出现意外结果:

But why does it do this? As a user I'd expect it to fail during conversion unless all octets are specified. Because it allows these conversions, unexpected results like this are possible when checking if a string is a valid IP address:

[bool]("10" -as [ipaddress]) #Outputs True


推荐答案

根据 https://msdn.microsoft.com/en-us/library/system.net.ipaddress.parse.aspx?f=255&MSPPError=-2147217396

ipString中的部分数量(每个部分用句点分隔)决定了IP地址的构造方式。单部分地址直接存储在网络地址中。 两部分地址,便于指定A类地址,将前导部分放在网络地址的最右边三个字节的第一个字节和尾部中。三部分地址,便于指定B类地址,将第一部分放在第一个字节中,第二部分放在第二个字节中,最后一部分放在网络地址的最右边两个字节中。

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.

这篇关于将部分IP地址字符串转换为IP地址对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆