IPAddress.[Try]Parse parses 192.168 to 192.0.0.168

断了今生、忘了曾经 提交于 2019-12-12 14:49:41

问题


I have the following scenario:

IPAddress ip;
IPAddress.TryParse("192.168", out ip);    
if(ip == null){//do something with IP}

I would expect the parsing to fail, instead it is parsed as "192.0.0.168". What am I missing here? (IPAddress.Parse works the same)


回答1:


From the documentation of Parse:

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. For example:

Number of parts and example ipString | IPv4 address for IPAddress
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



回答2:


The documentation, which includes similar examples to yours, is pretty clear:

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.

Number of parts and example ipString      IPv4 address for IPAddress    
====================================================================
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



回答3:


Type http://192.168 into your browser's address bar. What happens?

This is expected behaviour.



来源:https://stackoverflow.com/questions/12566664/ipaddress-tryparse-parses-192-168-to-192-0-0-168

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!