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
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.
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.
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.
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With