MC Emperor
MC Emperor

Reputation: 23037

Using same address and port for accepting and connecting in Java

(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?

Upvotes: 0

Views: 157

Answers (2)

AlexR
AlexR

Reputation: 115388

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.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533820

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.

Upvotes: 1

Related Questions