Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IPAddress.TryParse returns false

I have a string with IP Address which is

clientId = "172.19.200.29:10308"

I need to generate IPAddress object from it.Tried the following

    IPAddress clientIpAddr;
    if (IPAddress.TryParse(clientId, out clientIpAddr)) //<-returns false
//clientIpAddr is null

What could be wrong

like image 964
Yakov Avatar asked Jun 19 '26 04:06

Yakov


2 Answers

It's not an IP address, it's an IP address and port

try

if (IPAddress.TryParse(clientId.Split(':')[0], out clientIpAddr))

If you want IPv6 support

 var arr = clientId.Split(':');
 clientId = arr.Length <= 2 ? arr[0] : string.Join(":", arr.Take(8).ToArray());
 if (IPAddress.TryParse(clientId, out clientIpAddr))
like image 157
Bob Vale Avatar answered Jun 21 '26 17:06

Bob Vale


The IPAddress class should only contain the IP (without the port). You might be confused with the IPEndPoint class, which contains both IP and port:

Instantiate the IPAddress object as the following:

string clientId = "172.19.200.29:10308";
IPAddress clientIpAddr;
var success = IPAddress.TryParse(clientId.Split(':')[0], out clientIpAddr);

If required, you can instantiate the IPEndPoint as the following:

// Assuming that both ip and port are valid.
int port = int.Parse(clientId.Split(':')[1]);

var endpoint = new IPEndPoint(clientIpAddr, port);
like image 28
Aviran Cohen Avatar answered Jun 21 '26 18:06

Aviran Cohen



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!