Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IPAddress.TryParse returning undesired result

Tags:

c#

.net

vb.net

I have a function that returns if a given ip address is valid or not using the IPAddress class. I was testing it and it returns valid(true) even when I pass "0123456" or "11111" or "99999" without a dot as argument. I wrote it in VB.net and C# with the same result.

// C#
public bool CheckIpAddress(string ipAddr)
{
    IPAddress ip = null;
    return IPAddress.TryParse(ipAddr,out ip);
}

  // VB.net
  Public Function CheckIpAddress(ipAddr As String) As Boolean
        Dim ip As IPAddress = Nothing

        Return Net.IPAddress.TryParse(ipAddr, ip)
    End Function

Could somebody explain me why is this happening. I have matched my code with some sources through the internet and is fine.


1 Answers

IP Address is just 32 bit number, so 11111 is definitely a correct IP Address. Dots in IP Address are there just to make reading them easier for humans. They are not required.

IP addresses are binary numbers, but they are usually stored in text files and displayed in human-readable notations, such as 172.16.254.1 (for IPv4), and 2001:db8:0:1234:0:567:8:1 (for IPv6).

from IP address - Wikipedia

That's why IPAddress.TryParse returns true.

It's even described on MSDN: IPAddress.Parse Method

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.

There is also an example (see the first one):

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
like image 130
MarcinJuraszek Avatar answered Apr 02 '26 06:04

MarcinJuraszek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!