C#.Net Socket网络程序连接异常求助:指定IP端口连接问题
排查C# .NET Socket程序的Socket Exception问题
先帮你梳理下核心问题:你提到要连接目标IP 169.254.74.65:7998,本地IP是169.254.74.63,但你的代码用了服务端监听组件TcpListener,还错误绑定了目标IP,这是引发异常的关键原因之一,下面给你拆解分析和修复方案:
1. 代码核心错误:混淆服务端/客户端角色,绑定IP错误
TcpListener是服务端用来监听本地端口、等待客户端发起连接的组件,如果你需要主动连接目标服务器,应该用TcpClient;如果确实是要做服务端,那必须绑定自己的本地IP,而不是目标服务器的IP。
分两种场景修复:
场景一:你要做服务端(监听本地端口,等待目标IP的客户端连接)
修正绑定的IP为你的本地IP,完善后的代码如下:
using System; using System.Net; using System.Net.Sockets; class MyTcpListener{ public static void Main(){ TcpListener server = null; try{ Int32 port = 7998; // 绑定本地IP,或者用IPAddress.Any监听所有本地网卡 IPAddress localAddr = IPAddress.Parse("169.254.74.63"); server = new TcpListener(localAddr, port); server.Start(); Console.WriteLine("服务端已启动,等待客户端连接..."); Byte[] bytes = new Byte[500]; String data = null; while (true){ // 阻塞等待客户端连接 TcpClient client = server.AcceptTcpClient(); Console.WriteLine("客户端已连接"); NetworkStream stream = client.GetStream(); int i; // 读取客户端发送的数据 while ((i = stream.Read(bytes, 0, bytes.Length)) != 0){ data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); Console.WriteLine($"收到数据: {data}"); // 可选:给客户端返回响应 byte[] response = System.Text.Encoding.ASCII.GetBytes("消息已接收"); stream.Write(response, 0, response.Length); } client.Close(); } } catch (SocketException e){ Console.WriteLine($"Socket异常: {e.Message}"); Console.WriteLine($"错误码: {e.ErrorCode}"); // 错误码能帮你快速定位问题 } finally{ server?.Stop(); } } }
场景二:你要做客户端(主动连接目标服务器169.254.74.65:7998)
改用TcpClient实现客户端逻辑,示例代码如下:
using System; using System.Net.Sockets; using System.Text; class MyTcpClient { static void Main(string[] args) { try { string targetIp = "169.254.74.65"; int targetPort = 7998; // 主动连接目标服务器 using TcpClient client = new TcpClient(targetIp, targetPort); Console.WriteLine("已连接到目标服务器"); // 获取网络流用于收发数据 using NetworkStream stream = client.GetStream(); // 发送测试数据 string sendMsg = "来自客户端的测试消息"; byte[] sendData = Encoding.ASCII.GetBytes(sendMsg); stream.Write(sendData, 0, sendData.Length); Console.WriteLine($"已发送: {sendMsg}"); // 接收服务器响应 byte[] recvData = new byte[500]; int bytesRead = stream.Read(recvData, 0, recvData.Length); string recvMsg = Encoding.ASCII.GetString(recvData, 0, bytesRead); Console.WriteLine($"收到响应: {recvMsg}"); } catch (SocketException e) { Console.WriteLine($"Socket异常: {e.Message}"); Console.WriteLine($"错误码: {e.ErrorCode}"); } } }
2. 其他常见排查步骤
即使修正了代码,仍可能遇到Socket Exception,你可以按以下步骤排查:
- 检查端口占用:用命令
netstat -ano | findstr :7998(Windows)或lsof -i :7998(Linux/macOS)查看7998端口是否被其他程序占用,若被占用,可更换端口或关闭占用程序。 - 测试网络连通性:先执行
ping 169.254.74.65,如果ping不通,说明网络链路存在问题(比如网线未插、网卡配置错误),需先解决网络连通问题。 - 检查防火墙设置:Windows防火墙或第三方防火墙可能拦截了端口通信,可临时关闭防火墙测试,或在防火墙上添加允许7998端口的规则。
- 利用错误码定位:在catch块中打印
e.ErrorCode,不同错误码对应具体问题:- 10048:端口已被占用
- 10049:无法绑定指定IP(原代码的核心问题)
- 10060:连接超时(客户端场景常见,说明目标服务器未监听端口或网络不通)
内容的提问来源于stack exchange,提问作者Sayan Sen
相关产品推荐
相关产品推荐

