IPAddress.TryParse returns false

Yakov picture Yakov · Mar 23, 2014 · Viewed 7.6k times · Source

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

Answer

Bob Vale picture Bob Vale · Mar 23, 2014

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