0
votes

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("192.168.1.101", 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);
        clientSocket.send(sendPacket);
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket);
        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("192.168.1.215", 6060);
    serverSocket.bind(serverAddress);
    byte[] receiveData = new byte[504];
    byte[] sendData = new byte[504];
    while (true) {
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        serverSocket.receive(receivePacket);
        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);
        serverSocket.send(sendPacket);
    }
}

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?

1

1 Answers

1
votes

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).