0

(This might have been asked a thousand times, but I do not get it straight.)

Suppose I have the following snippet:

InetAddress localAddress = InetAddress.getByName("192.168.1.10");
int localPort = 65000;
InetAddress targetAddress = InetAddress.getByName("192.168.1.20");
int targetPort = 65000;

// Create a new serversocket 
ServerSocket ss = new ServerSocket(localPort, 50, localAddress);
// Wait for an incoming connection...
Socket acceptedSocket = ss.accept();
// Do something with the accepted socket. Possibly in a new thread.

Set up new connection...
Socket socket = new Socket(targetAddress, targetPort, localAddress, localPort);
// Write something to the socket.

Now can I use the same address and port for both accepting an incoming connection and connecting to an address? If it can, then how? If not, then why not? According to this post, ports can be shared, so it shouldn't be a problem.

How does it work?

Community
  • 1
  • 1
MC Emperor
  • 22,334
  • 15
  • 80
  • 130

2 Answers2

1

You can only establish a connection by having the connecting socket use the same address and port. (Ignoring the use of multi-homed servers)

A single connection is a unique combination of both the source address+port and destination address+port, so you can have the same destination if you have a different source.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

In other words, can you write server program that that contains client connecting to itself? The answer is yes, surely. All integration tests do this running in-process server and connecting to it.

user207421
  • 305,947
  • 44
  • 307
  • 483
AlexR
  • 114,158
  • 16
  • 130
  • 208