Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IPAddress.Parse() using port on IPv4

I'm trying to parse a string containing an IP address and a port using IPAddress.Parse. This works well with IPv6 addresses but not with IPv4 addresses. Can somone explain why this happens?

The code I'm using is:

IPAddress.Parse("[::1]:5"); //Valid
IPAddress.Parse("127.0.0.1:5"); //null
like image 630
Francisco Silva Avatar asked Feb 11 '11 12:02

Francisco Silva


People also ask

What is parse IP address?

The static Parse method creates an IPAddress instance from an IP address expressed in dotted-quad notation for IPv4 and in colon-hexadecimal notation for IPv6.

How do you check IP address is IPv4 or IPv6 Python?

To use the ipaddress module, first import it into your Python code. Next, call the . ip_address() method on the ipaddress class, passing it an IP string. If the IP string passed is a valid IPv4 address or valid IPv6 address, the ipaddress module will use the string to create a new IP address object.

How do you write an IP address in Python?

Python provides ipaddress module which is used to validate and categorize the IP address according to their types(IPv4 or IPv6). This module is also used for performing wide range of operation like arithmetic, comparison, etc to manipulate the IP addresses.


2 Answers

Uri url;
IPAddress ip;
if (Uri.TryCreate(String.Format("http://{0}", "127.0.0.1:5"), UriKind.Absolute, out url) &&
   IPAddress.TryParse(url.Host, out ip))
{
    IPEndPoint endPoint = new IPEndPoint(ip, url.Port);
}
like image 97
abatishchev Avatar answered Oct 13 '22 06:10

abatishchev


This happens because the port is not part of the IP address. It belongs to TCP/UDP, and you'll have to strip it out first. The Uri class might be helpful for this.

like image 11
Alex J Avatar answered Oct 13 '22 04:10

Alex J