C#捕获本地内网指定端口读取响应请求数据实例代码
时间: 2024-12-26 22:29:11 浏览: 4
在C#中,你可以使用System.Net套接字(Socket)类来监听和处理来自特定端口的网络连接。以下是一个简单的例子,展示如何在一个本地IP地址上捕获并读取内网指定端口的数据:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
public class NetworkListener
{
private static readonly IPAddress ipAddress = IPAddress.Parse("192.168.1.1"); // 内网IP地址
private static readonly int portNumber = 8080; // 监听的端口号
public static void Main()
{
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 绑定到指定的IP地址和端口
listener.Bind(new IPEndPoint(ipAddress, portNumber));
// 设置为监听模式
listener.Listen(10);
Console.WriteLine($"Server started on {ipAddress}:{portNumber}");
while (true)
{
Socket handler = listener.Accept();
Console.WriteLine($"Accepted connection from {handler.RemoteEndPoint}");
// 接收数据
byte[] buffer = new byte[1024];
int bytesRead = handler.Receive(buffer);
string receivedData = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine($"Received data: {receivedData}");
// 关闭连接并释放资源
handler.Close();
}
}
}
阅读全文