首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在c#中获取tcp客户端的ip和端口并显示出来?

在C#中获取TCP客户端的IP和端口并显示出来,可以通过以下步骤实现:

  1. 创建一个TCP服务器,监听指定的端口。
  2. 当有客户端连接到服务器时,通过AcceptTcpClient方法接受客户端连接,并获取TcpClient对象。
  3. 通过TcpClient对象的Client属性获取Socket对象。
  4. 使用Socket对象的RemoteEndPoint属性获取客户端的IP地址和端口信息。

下面是一个示例代码:

代码语言:csharp
复制
using System;
using System.Net;
using System.Net.Sockets;

class Program
{
    static void Main(string[] args)
    {
        // 创建TCP服务器
        TcpListener server = new TcpListener(IPAddress.Any, 8888);
        server.Start();
        Console.WriteLine("服务器已启动,等待客户端连接...");

        // 接受客户端连接
        TcpClient client = server.AcceptTcpClient();
        Console.WriteLine("客户端已连接");

        // 获取客户端的IP地址和端口
        IPEndPoint clientEndPoint = (IPEndPoint)client.Client.RemoteEndPoint;
        string clientIP = clientEndPoint.Address.ToString();
        int clientPort = clientEndPoint.Port;
        Console.WriteLine("客户端IP地址:{0}", clientIP);
        Console.WriteLine("客户端端口:{0}", clientPort);

        // 关闭连接
        client.Close();
        server.Stop();

        Console.ReadLine();
    }
}

在上述示例中,我们创建了一个TCP服务器,监听本地的8888端口。当有客户端连接到服务器时,通过AcceptTcpClient方法接受客户端连接,并获取TcpClient对象。然后,通过TcpClient对象的Client属性获取Socket对象。最后,使用Socket对象的RemoteEndPoint属性获取客户端的IP地址和端口信息,并将其显示在控制台上。

请注意,这只是一个简单的示例,实际应用中可能需要进行错误处理、异常处理以及其他相关的逻辑。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券