Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why IPAddress.Parse("192.168.001.001") works while IPAddress.Parse("192.168.001.009") don't?

Tags:

c#

.net-4.5

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 instead of 127.0.0.1

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!!!

It also fails for 192.168.001.018, but works for .017, .016 down to 010!

It works for 192.168.001.8 or .8 and also 192.168.001.18 and .19...

Is this a bug in the CLR? Or am I missing something stupid?

Just try:

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!
like image 831
Loudenvier Avatar asked Oct 08 '15 22:10

Loudenvier


1 Answers

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.

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.

A possible quick and dirty solution would be to search for the regex /\.0*/ and replace it with "."

You can find more information on the wikipedia entry for Dot-decimal-notation:

A popular implementation of IP networking, originating in 4.2BSD, contains a function inet_aton() for converting IP addresses in character strings representation to internal binary storage. In addition to the basic four-decimals format and full 32-bit addresses, it also supported intermediate syntaxes of octet.24bits (e.g. 10.1234567; for Class A addresses) and octet.octet.16bits (e.g. 172.16.12345; for Class B addresses). It also allowed the numbers to be written in hexadecimal and octal, by prefixing them with 0x and 0, respectively. These features continue to be supported by software until today, even though they are seen as non-standard. But this also means addresses where an IP address component is written with a leading zero digit may be interpreted differently by different programs: some will ignore the leading zero, some will interpret the number as octal.

like image 100
pupeno Avatar answered Oct 16 '22 09:10

pupeno