C#实时判断TCP客户端IP地址和端口号是否连接成功
可以使用TcpClient类的Connected属性来判断TCP客户端是否连接成功。如果Connected属性为true,则表示连接成功。而要获取客户端的IP地址和端口号,则可以使用TcpClient类的Client属性的RemoteEndPoint属性。以下是示例代码:
using System;
using System.Net;
using System.Net.Sockets;
class Program
{
static void Main(string[] args)
{
TcpClient client = new TcpClient();
client.Connect("localhost", 8888); // 连接服务器
// 判断是否连接成功
if (client.Connected)
{
Console.WriteLine("连接成功");
// 获取客户端IP地址和端口号
IPEndPoint remoteEndPoint = (IPEndPoint)client.Client.RemoteEndPoint;
Console.WriteLine($"客户端IP地址:{remoteEndPoint.Address}");
Console.WriteLine($"客户端端口号:{remoteEndPoint.Port}");
}
else
{
Console.WriteLine("连接失败");
}
Console.ReadLine();
}
}
``
原文地址: https://www.cveoy.top/t/topic/fHZR 著作权归作者所有。请勿转载和采集!