在 C# 中,可以使用 TcpClient 类和 TcpListener 类来实现 TCP 客户端和服务端的连接。可以通过以下步骤来判断 TCP 客户端 IP 地址和端口号是否连接成功:

  1. 创建 TcpClient 对象,并使用指定的 IP 地址和端口号连接到 TCP 服务器:
TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse('192.168.0.1'), 8888);
  1. 检查 TcpClient 对象的 Connected 属性,如果为 true,则表示连接成功:
if (client.Connected)
{
    // 连接成功
}
else
{
    // 连接失败
}
  1. 获取 TcpClient 对象的本地 IP 地址和端口号,以确认连接成功后的本地地址和端口号:
IPEndPoint localEP = (IPEndPoint)client.Client.LocalEndPoint;
Console.WriteLine('Local IP: {0}, Local Port: {1}', localEP.Address, localEP.Port);

完整示例代码:

using System;
using System.Net;
using System.Net.Sockets;

class Program
{
    static void Main()
    {
        TcpClient client = new TcpClient();
        client.Connect(IPAddress.Parse('192.168.0.1'), 8888);

        if (client.Connected)
        {
            IPEndPoint localEP = (IPEndPoint)client.Client.LocalEndPoint;
            Console.WriteLine('Connected to server. Local IP: {0}, Local Port: {1}', localEP.Address, localEP.Port);
        }
        else
        {
            Console.WriteLine('Failed to connect to server.');
        }

        Console.ReadLine();
    }
}
C# 实时判断 TCP 客户端连接成功:IP 地址和端口号

原文地址: https://www.cveoy.top/t/topic/onEi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录