Socket.connect()到0.0.0.0:Windows与Mac [英] Socket.connect() to 0.0.0.0: Windows vs. Mac

查看:663
本文介绍了Socket.connect()到0.0.0.0:Windows与Mac的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下以下代码:

String hostName = "0.0.0.0";
int port = 10002;
int timeout = 5000;
Socket socket = new Socket();
socket.connect(new InetSocketAddress(hostName, port), timeout);

在Mac上它工作正常并执行连接(即使没有在端口10002上运行) Windows我得到以下异常:

On the Mac it works fine and executes the connect (even with nothing running on port 10002) and on Windows I get the following exception:

java.net.SocketException: Permission denied: connect

这里的区别是什么以及Windows的替代方案是什么?这用于单元测试。

What's the difference here and what would be the alternative on Windows? This is used in unit tests.

问候

Jonas

推荐答案

以防其他人偶然发现这个问题,我正在回答。

Just in case somebody else stumbles upon this question, I am answering it.

不幸的是,连接到任何人Windows上不允许使用该地址。

Unfortunately, connecting to the any address is not allowed on Windows.

Winsock函数 connect 将返回错误代码 WSAEADDRNOTAVAIL
[远程地址不是有效地址(例如INADDR_ANY或in6addr_any)],
,如 Windows API文档

The Winsock function connect will return the error code WSAEADDRNOTAVAIL [The remote address is not a valid address (such as INADDR_ANY or in6addr_any)], as stated at the Windows API Documentation:


如果name参数指定的结构的地址成员用零填充,connect将返回错误WSAEADDRNOTAVAIL。

If the address member of the structure specified by the name parameter is filled with zeros, connect will return the error WSAEADDRNOTAVAIL.

所以不使用任何本地主机地址,我认为你想要做的事情在Windows上是不可能的(虽然我是如果Unix行为是一个错误或有意的话,请执行。)。

So without using any localhost address, I think what you are trying to do will not be possible on Windows (Though I wonder if the Unix behavior is a bug or intentional.).

我建议设置更多的环回接口,正如Mark Reed在他的评论

I would suggest setting up more loopback interfaces, as Mark Reed suggested in his comment.

这篇关于Socket.connect()到0.0.0.0:Windows与Mac的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆