Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

java - Socket.connect() to 0.0.0.0: Windows vs. Mac

Imagine the following code:

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

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

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

Regards

Jonas

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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:

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

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.).

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...