How exactly does ServerSocket behave in these scenarios?

Let's say we have a ServerSocket and we run accept (). The client connects and a new socket is created with the same local port as the ServerSocket. Let's say the client is sending data to this socket. It reaches the port and reaches the Java application. How does the data here get to the correct socket?

Let's say that two computers are hidden behind the same public IP address through NAT. Will this create problems? It would seem that the same computer is trying to create a connection (same public ip and same port), I feel like I am missing something here.

+3


source to share


2 answers


A socket connects a local address and port to a remote address and port. This is the key: you can accept multiple connections from the same IP as long as the port is different. (For example, you can open the same web page in two different browser tabs because they connect to two different client ports.)

NAT is responsible for ensuring that two connections from two separate computers receive a different address / port combination. If they map to the same public IP address, NAT will have to assign a different local port for these connections. As a server, you don't have to worry about this: you just see two different address / port combinations connecting your server address / port, so they are different sockets.



In Java, a ServerSocket

acts as an entry point. It binds to your server address and port, so it's kind of a half-socket pattern. When the client connects to its address and port, a "full" Socket

with half of them is created, and now the server and client can start talking. See how TCP / UDP connections work if it isn't clear enough yet.

+6


source


You cannot have two servers with the same pair (IP, port). If behind NAT NAT has to assign a different public port for each local server, it cannot assign it to both.



-1


source







All Articles