Smig
Smig

Reputation: 693

Improving the way I get server's ip address from the client

MulticastSocket multicast_socket = new MulticastSocket(Dialogos.MULTICAST_PORTA);
InetAddress group = InetAddress.getByName(Dialogos.MULTICAST_IP_GRUPO);
multicast_socket.joinGroup(group);
byte[] msg = new byte[1024];
DatagramPacket packet = new DatagramPacket(msg, msg.length);
multicast_socket.receive(packet);

In the code above, the server is receiving a request from a client, via multicast. The server is now supposed to let the client know "where" it is. This is just one method for the client to guess where to connect, it's not completely dependent on it.

The server can be installed on many different environments though, so I don't know which interface/address will be used to communicate with the client. Therefore, to tell the client where it is, I'm compiling all the available ip addresses in the server and sending them all back in a multicast, so that the client can try them out until one succeeds.

My question: Is there a way to improve this mechanism? I wonder if, on the server app, I could get the local ip that received the multicast from the client, then I'd know which one to send back. Can't find methods that do that though. Maybe some way to attempt a connection to the client just to know which local address it would pick to do so?

Upvotes: 3

Views: 166

Answers (1)

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84159

Just send unicast UDP packet back to the client, and the client will be able to extract the source IP address. That will ensure it's the address on the interface/route where client and server can talk to each other. You will need that packet to tell the listening port number somehow, of course.

Upvotes: 2

Related Questions