c# 监控5900 port哪个IP访问了这个IP就显示在Form里面如果断开了5900连接也显示在Form里面
下面是一个简单的示例代码,用于在C#中监控5900端口,显示访问和断开连接的IP地址在一个窗体(Form)中:
using System;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
namespace PortMonitor
{
public partial class MainForm : Form
{
private TcpListener tcpListener;
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
try
{
// 监听5900端口
tcpListener = new TcpListener(IPAddress.Any, 5900);
tcpListener.Start();
// 异步接受客户端连接
tcpListener.BeginAcceptTcpClient(AcceptCallback, null);
// 显示监听信息
LogMessage("Started listening on port 5900...");
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
private void AcceptCallback(IAsyncResult ar)
{
try
{
// 接受客户端连接
TcpClient client = tcpListener.EndAcceptTcpClient(ar);
IPAddress clientIP = ((IPEndPoint)client.Client.RemoteEndPoint).Address;
// 显示连接信息
LogMessage("Connected client IP: " + clientIP);
// 继续异步接受下一个客户端连接
tcpListener.BeginAcceptTcpClient(AcceptCallback, null);
// 异步接收客户端数据
byte[] buffer = new byte[1024];
client.GetStream().BeginRead(buffer, 0, buffer.Length, ReadCallback, new Tuple<TcpClient, byte[]>(client, buffer));
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
private void ReadCallback(IAsyncResult ar)
{
try
{
// 获取客户端和接收缓冲区
Tuple<TcpClient, byte[]> state = (Tuple<TcpClient, byte[]>)ar.AsyncState;
TcpClient client = state.Item1;
byte[] buffer = state.Item2;
// 读取客户端数据
int bytesRead = client.GetStream().EndRead(ar);
if (bytesRead > 0)
{
// 处理客户端数据
// 继续异步接收客户端数据
client.GetStream().BeginRead(buffer, 0, buffer.Length, ReadCallback, state);
}
else
{
// 客户端断开连接
IPAddress clientIP = ((IPEndPoint)client.Client.RemoteEndPoint).Address;
// 显示断开连接信息
LogMessage("Disconnected client IP: " + clientIP);
// 关闭客户端连接
client.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
private void LogMessage(string message)
{
if (InvokeRequired)
{
Invoke(new Action<string>(LogMessage), message);
}
else
{
listBoxLog.Items.Add(message);
}
}
}
}
此代码创建一个简单的Windows窗体应用程序,使用TcpListener监听5900端口,并在连接和断开连接时显示IP地址。连接和断开连接的信息将显示在listBoxLog控件中。
请确保在窗体中正确设置了MainForm_Load事件处理程序和listBoxLog控件
原文地址: https://www.cveoy.top/t/topic/hNQ9 著作权归作者所有。请勿转载和采集!