Marcus Persson Marcus Persson -3 years ago 153
Java Question

Java UDP client/server over internet does not work

I'm trying to implement an UDP client and server that send messages back and forth.

My server is set up on the local IP .215 on port 6060 while my client is set up on local IP .101 on port 6061. Both ports have been forwarded on the router (UDP). I tested the ports using some online tool and it confirmed that the ports are open.

The server starts by listening, meaning that the client will send the first message. The communication works as intended when the client sends its messages to the local IP .215 on port 6060. However, when it sends to the internet IP, using the same port, nothing is received by the server. I do not understand why.

Below is my code for the client:

public static void main(String args[]) throws Exception {
DatagramSocket clientSocket = null;
clientSocket = new DatagramSocket(null);
clientSocket.bind(new InetSocketAddress("", 6061));
InetAddress serverIPAddress = InetAddress.getByName("my.internet.ip");
int serverPort = 6060;
byte[] sendData = new byte[504];
byte[] receiveData = new byte[504];
while (true) {
String sentence = "A" + Double.toString(Math.random()) + "A";
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverIPAddress, serverPort);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
String modifiedSentence = new String(receivePacket.getData());

Below is my code for the server:

public static void main(String[] args) throws IOException {
DatagramSocket serverSocket = new DatagramSocket(null);
InetSocketAddress serverAddress = new InetSocketAddress("", 6060);
byte[] receiveData = new byte[504];
byte[] sendData = new byte[504];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);

I removed unnecessary code e.g. console prints etc to make it more readable.

Any ideas why it does not work, that is, to send messages over internet IP?

Answer Source

Your router does not use NAT reflection which is the feature where the router allows access of a service via the public IP address from inside the local network(using the port forwarding rules internally).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download