Question

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

Was it helpful?

Solution

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

OTHER TIPS

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top