1
votes

I have a server running a public IP with no NAT. It receives UDP packets and I want to send them to each client that's connected.

The client or clients would behind a NAT.

I've read about UDP hole punching but it doesn't seem like exactly what I want. I'm not trying to send from client to client. I want data flow to go from client -> server -> all clients.

The Client

// Init TCP Socket
connection = new Socket(connectionAddress, 54540);

// Create receive socket
DatagramSocket socketReceive = new DatagramSocket(54541);

The Server


// Receive socket
receiveAudioSocket = new DatagramSocket(54541);

// Thread to handle new received packets
ServerAudioReceiverWorker audioReceiverWorker = new ServerAudioReceiverWorker(receiveAudioSocket, this);
audioReceiverWorker.start();

// TCP Socket
serverSocket = new ServerSocket(54540);
System.out.println("Server has started");

This is the basic setup for my client server.

I expected that if I send a UDP packet from the client to the server public IP. The router would add a NAT rule for port 54541 on the clients network to receive UDP packets sent from the server back to the public IP of the client and port 54541. It doesn't seem like it's working that way.

I guess that's because the NAT rule being assigned is given a specific port for requests to the public IP to target the local IP. I'm not sure how to find the port that the server should send the packets to for each client.

Do I need to use UPnP to open the port on the client network and let the server know which port to send packets to.

1

1 Answers

2
votes

NAT requires that the client behind the NAT router first initiates a connection to the external server so that the NAT router can create a state for the address and port translation. The reply from the server must exactly match the state since otherwise no translation back can be done by the NAT router.

This means:

  • You must use the same socket for sending and receiving in the client, i.e. you can not expect the reply back on a different port as you currently do.
  • The server must send the messages to exactly the same IP and port which were used as source by the clients to contact the server and it must be send from exactly the same IP and port which the clients used as destination - this is usually done by using the same socket on the server.
  • It is not possible to send messages to clients which have not recently contacted the server, because in this case there is no matching state in the clients NAT router (it expires after some time).