将部分IP地址字符串转换为IP地址对象

编程入门 行业动态 更新时间:2024-10-27 09:43:10
本文介绍了将部分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

推荐答案

根据 msdn.microsoft/en-us/library/system.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地址对象

本文发布于:2023-06-10 05:43:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/608227.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:地址   转换为   字符串   对象   IP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!