andig
andig

Reputation: 13868

Why doesn't stream_socket_server block the port from additional sockets on Windows?

I have a reactphp script opening multiple ports for listening. Code comes down to trying to open a socket on port x, if occupied choose port+1.

I've found that I can open multiple sockets for the same port without error message which makes the above method of finding a "free" port invalid:

var_dump($s1 = stream_socket_server("tcp://127.0.0.1:7777", $errno, $errstr));
var_dump($s2 = stream_socket_server("tcp://127.0.0.1:7777", $errno, $errstr));

Both calls return a resource with different id. Why does this happen and is it possible that a port already has an open socket from the same process (without keeping book on the sockets)?

PS.: Opening two sockets from different processes fails as expected.

Related questions: Multiple UDP Sockets to listen for specific source on the same port

Update

See https://3v4l.org/6eWY1, it seems the decribed behaviour applies to Windows versions of PHP only.

Upvotes: 1

Views: 2765

Answers (2)

Mathieu de Lorimier
Mathieu de Lorimier

Reputation: 1015

Have a look at this technique to test if a port is open.

I get the same results with your code and this technique works for me to identify if a port was already open by the same process.

That could be an option if you don't mind the overhead.

Upvotes: 2

Axe
Axe

Reputation: 692

FYI I do not know PHP and I primarily use Linux, so your mileage may vary. It seems though that I might help you with some tcp knowledge. If you already know this, forgive me and ignore my answer ;)

So I don't know how you connected to your server socket and how your server handled the connection, but if it is programmed correctly your server will not occupy the port, hence blocking future connections. You can of course do that if you want to.

Normally when you create a server, you want to have 1 known port, so that multiple clients can connect to it (like port 80 for http). The server uses 'listen' to listen for connections, followed by an 'accept' and finally a 'close'. The accept makes sure that you can get multiple connections via your server port.

Btw:

  • you can find a free port by opening a socket on port 0.
  • you can handle multiple sockets via 'select'
  • a nice book to read up on sockets is Working with Tcp sockets by Jesse Storimer (FYI I don't have stocks, only the book ;). But there are many intros to socket programming if your google fu is with you.

Upvotes: 0

Related Questions