繁体   English   中英

TCP客户端无法使用框架4.6.1绑定到套接字中的端口0

[英]TCP client fails to bind to port 0 in socket using framework 4.6.1

我有一个正在运行的应用程序,它使用Socket通信连接到某个端口上的服务器。 我已经将该应用程序从框架2.0(Visual Studio)移植到框架4.5,通过所有中间框架没有任何问题。

现在,使用visual studio 15和framework 4.6.1,套接字不再连接。 搜索到代码,我发现问题是socket.Bind,当本地端口为0时抛出异常。值得注意的是,通常不需要绑定本地端口,但是当你有多个网络适配器时,并且服务器只允许您的一个IP连接,您需要绑定套接字必须使用的适配器(或IP)来启动其连接,否则,套接字将使用随机IP或顶部的IP 。 评论'绑定'将正常工作,但我们失去了指定其他本地IP进行连接的能力。 遗憾的是,我的IP不是默认选择的IP,因此我无法再在框架4.6.1中进行连接

任何人都可以帮助解决这个问题吗?

// IPEndPoint is the local IP to use for connection. Port 0 means random port
IPEndPoint localHost = new IPEndPoint(IPAddress.Parse("123.xxx.xxx.126"), 0);

// now we bind to force the socket to use the provided IP in IPEndPoint
_socket.Bind(localHost);

// Finally, we connect to the server using the bound IP and Port (random)
_socket.Connect("123.xxx.xxx.130",8080);

_socket.Bind will throw the following error (only in fw 4.6.1)

{“请求的地址在其上下文中无效”}本机错误代码:10049

当然,当用作客户端时,对套接字上的错误10049没什么帮助。

更换:

IPEndPoint localHost = new IPEndPoint(IPAddress.Parse("123.xxx.xxx.126"), 0);

IPEndPoint localHost = new IPEndPoint(IPAddress.Any, 0);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM