You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中正在运行的TcpListner变量停止后如何复用绑定新IP?

C# 不新建TcpListener变量实现重启后重绑定IP的方案

实现步骤

  • 首先停止当前运行的TcpListener实例,释放已占用的IP和端口资源
    调用listener.Stop()方法即可关闭底层监听Socket,清空待处理的连接队列。如果有正在运行的异步接受连接逻辑(如AcceptTcpClientAsync()),建议先通过CancellationToken取消相关操作,避免后续抛出对象已释放异常。
  • 重新配置底层监听Socket的绑定规则
    TcpListener公开的Server属性对应其底层使用的Socket实例,我们可以通过重置该实例完成新端点的绑定,无需声明新的TcpListener变量。

代码示例

.NET Core / .NET 5+ 版本

// 你的现有运行中实例
TcpListener listener;

// 1. 停止现有监听
listener.Stop();

// 2. 定义新的绑定端点
IPAddress newBindIp = IPAddress.Parse("192.168.3.20");
int newBindPort = 9000;
IPEndPoint newEndPoint = new IPEndPoint(newBindIp, newBindPort);

// 3. 重置底层Socket并绑定新端点
listener.Server = new Socket(newEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listener.Server.Bind(newEndPoint);

// 4. 启动新的监听
listener.Start();

.NET Framework 兼容版本

.NET Framework中TcpListener.Server为只读属性,此时直接替换现有变量的实例引用即可,不需要新建变量:

// 1. 停止现有监听
listener.Stop();

// 2. 直接替换现有变量指向的实例,无需声明新变量
IPAddress newBindIp = IPAddress.Parse("192.168.3.20");
int newBindPort = 9000;
listener = new TcpListener(newBindIp, newBindPort);

// 3. 启动监听
listener.Start();

注意:如果绑定新端口时抛出访问被拒绝异常,需要确认端口未被其他进程占用,或是当前程序有绑定该IP/端口的权限。

内容的提问来源于stack exchange,提问作者StackingGrandma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 14:18:03