質問

I was wondering, how multiple applications can use the same network port. AFAIK in TCP protocol 1 port is assigned to 1 socket connection. So how, for example, more than one internet browser can use ports 80/8080 at the same time? Can I bind more than one socket to the same port? How can I do that in C++?

役に立ちましたか?

解決

A socket connection is uniquely identified by a combination of its local IP:Port and remote IP:Port. Multiple apps can be bound to the same local IP:Port as long as they are each connected to a different remote IP:Port.

If a local IP:Port is already bound for listening (bind() and listen() have been called for it), other sockets can still bind() to that same local IP:Port but only if the SO_REUSEADDR (and on some platforms, SO_REUSEPORT) socket option is used. Otherwise, the bind() fails with an "already in use" error.

When multiple client sockets connect() to the same remote IP:Port, a local binding is typically not specified, which allows connect() to perform an implicit bind() to a random available local IP:Port to avoid conflicts with other connections. If bind() is explicitly called and succeeds, and then connect() is called to connect to a remote IP:Port that is already connected to the local IP:Port, connect() will fail.

他のヒント

A TCP port can only have a single socket listening for connections. When a connection is made via accept() or friends, a new socket is generated, that represents this connection, while the single original listening socket keeps listening.

In TCP, which is a stateful protocol, a connection is defined uniquely by the tuple [source_ip, source_port, dest_ip, dest_port] (look at Eugen Rieck's comment above). So theoretically, each client(or set of clients behind a NAT) could connect to the server on any 16-bit port number (minus typically the ports from 0-1023).

When a web server is listening on port 80(for example) for incoming HTTP connections, each time the client tries to send an HTTP request to the server, the client initiates a TCP connection over a different client port. So the answer to how multiple applications can use the same network port is by having a different port on the other side.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top