假设采用TCP协议,clientSocket为Socket类型,它是服务器上已联入的客户端:

string clientIP=((IPEndPoint)clientSocket.RemoteEndPoint).Address.ToString();
string clientPort = ((IPEndPoint)clientSocket.RemoteEndPoint).Port.ToString();
Console.WriteLine("客户端IP:" + clientIP +".客户端端口:" + clientPort);
Console.WriteLine("客户端IP和端口(IP:PORT):" + clientSocket.RemoteEndPoint.ToString());

官方来源:Socket.RemoteEndPoint 属性 (System.Net.Sockets) | Microsoft Learn

官方代码:

s.Connect(lep);

// Using the RemoteEndPoint property.
Console.WriteLine(“I am connected to ” + IPAddress.Parse(((IPEndPoint)s.RemoteEndPoint).Address.ToString()) + “on port number ” + ((IPEndPoint)s.RemoteEndPoint).Port.ToString());

// Using the LocalEndPoint property.
Console.WriteLine(“My local IpAddress is :” + IPAddress.Parse(((IPEndPoint)s.LocalEndPoint).Address.ToString()) + “I am connected on port number ” + ((IPEndPoint)s.LocalEndPoint).Port.ToString());

作者 申佳明

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Captcha Code