开发者

How do you get the host address and port from a System.Net.EndPoint?

开发者 https://www.devze.com 2023-01-01 00:10 出处:网络
I\'m using a TcpClient passed to开发者_如何学JAVA me from a TcpListener, and for the life of me I can\'t figure out a simple way to get the address and port it\'s connected to.

I'm using a TcpClient passed to开发者_如何学JAVA me from a TcpListener, and for the life of me I can't figure out a simple way to get the address and port it's connected to.

The best I have so far is _client.Client.RemoteEndPoint.ToString(); which returns a string in the form FFFF::FFFF:FFFF:FFF:FFFF%00:0000. I've managed to extract the address and port using Regular Expressions, but this seems like overkill. What am I missing?


You can cast the EndPoint to an IPEndPoint

var ep = _client.Client.RemoveEndPoint as IPEndPoint;
if (ep != null)
{
    Console.WriteLine("Address: {0}", ep.Address);
    Console.WriteLine("Port: {0}", ep.Port);
}

You shouldn't really need the test for != null, cause you know that it'll always be IPEndPoint if you're connecting to an internet address...

0

精彩评论

暂无评论...
验证码 换一张
取 消