监听特定的端口c#

本文关键字:监听 | 更新日期: 2023-09-27 18:25:24

我想监听c#中的特定端口,但我不想在net中编写聊天程序。我只想监听一个端口并接收来自该端口的所有字节。我以前问过这个问题,但没有得到有用的答案。我再说一遍,我不想有客户端和服务器程序,我只想有一个在我的计算机上运行的程序,告诉我从特定端口接收到的字节,或者一个告诉我每个端口连接了什么IP的程序,比如CMD中的"netstat"命令。(我不想在C#程序中使用CMD命令)请帮帮我。

监听特定的端口c#

我认为这应该让你开始。这将向您显示与netstat:类似的信息

using System;
using System.Net;
using System.Net.NetworkInformation;
static void Main()
{
    IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
    TcpConnectionInformation[] tcpConnections = ipGlobalProperties.GetActiveTcpConnections();
    foreach (TcpConnectionInformation tcpConnection in tcpConnections)
    {
        Console.WriteLine("Local Address {0}:{1}'nForeign Address {2}:{3}'nState {4}",
                        tcpConnection.LocalEndPoint.Address,
                        tcpConnection.LocalEndPoint.Port,
                        tcpConnection.RemoteEndPoint.Address,
                        tcpConnection.RemoteEndPoint.Port,
                        tcpConnection.State);
    }
}

要收听端口,Microsoft在这里提供的示例代码应该会让你开始。

您需要一个嗅探器。查看Wireshark。