问题描述
我一直试图从API结果中解析IP地址,在该结果中,IPv4地址的四个Pat均以0(零)为前缀。像这样:
I'm stuck trying to parse IP addresses from a API result where each of the four pats of the IPv4 Address comes prefixed with 0 (zeroes). Something like this:
127.000.000.001而不是127.0.0.1
127.000.000.001 instead of 127.0.0.1
当我尝试解析192.168.001.009对于192.168.001.008,它也会失败,但对于001、007、006、005都有效!!!!
I started getting parse errors when trying to parse 192.168.001.009. It also fails for 192.168.001.008, but works for 007, 006, 005 up to 001!!!
对于192.168.001.018,它也会失败,但是对于.017 ,.016降到010!
It also fails for 192.168.001.018, but works for .017, .016 down to 010!
它适用于192.168.001.8或.8以及192.168.001.18和.19 ...
It works for 192.168.001.8 or .8 and also 192.168.001.18 and .19...
这是CLR中的错误吗?还是我想念一些愚蠢的东西?
Is this a bug in the CLR? Or am I missing something stupid?
只需尝试:
IPAddress.Parse("192.168.001.007"); // works
IPAddress.Parse("192.168.001.87"); // works
IPAddress.Parse("192.168.001.008"); // throws exception
IPAddress.Parse("192.168.001.19"); // works
IPAddress.Parse("192.168.001.019"); // throws exception
// and so on!
推荐答案
数字从0开始,因此被解释为八进制而不是十进制。这些不是C#文字,因此要由库以一种或另一种方式解释。
The numbers, since they are starting with 0, are being interpreted as octal instead of decimal. These are not C# literals, so it's up to the library to interpret it one way or another.
一种简单的测试方法是构造一个以 .010,解析它,您会看到它被解析为以.8结尾的ip。
A simple way to test it would be to construct an IP ending in ".010", parse it, and you'll see that it was parsed as an ip ending in .8.
一种可能的快速而肮脏的解决方案是搜索正则表达式 /\.0 * /
并替换
A possible quick and dirty solution would be to search for the regex /\.0*/
and replace it with "."
您可以在Wikipedia条目上找到点小数表示法的更多信息:
You can find more information on the wikipedia entry for Dot-decimal-notation:
这篇关于为什么IPAddress.Parse(“ 192.168.001.001”)不起作用,而IPAddress.Parse(“ 192.168.001.001”)却起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!