Search code examples
javanetwork-programmingblockingchanneldatagram

Java DatagramChannel - Cannot ping port from external network


I am writing a server which uses a DatagramChannel (non-blocking) to send/receive data. It works flawlessly on my local network, but if I try to connect to it using the client application from a different network (i.e. over the internet), I cannot reach it.

Whilst running, if I use http://ping.eu/port-chk/ to check the port, it says it's closed. I have forwarded the appropriate ports and adjusted firewalls to appropriate levels.

My code is as follows:

public void runServer(int portNo)
{

    try
    {
        serverChannel = DatagramChannel.open();
        ipAddress = InetAddress.getLocalHost();
        //ipAddress = InetAddress.getByName(getPublicIP());
        //serverChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); //Added in to try to fix
        serverChannel.socket().bind(new InetSocketAddress(portNo));
        serverChannel.configureBlocking(false);
        serverChannel.socket().setReceiveBufferSize(receiveBufferSize);
        serverChannel.socket().setSendBufferSize(sendBufferSize);
        //serverChannel.connect(new InetSocketAddress(ipAddress,portNo)); //Added in to try to fix

        serverRunning = true;
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }


}

The parts which are commented out have had no effect. The ipAddress variable in the example will fetch the local IP, where as the commented-out version will get the public IP of the computer.

If you could help me find out why I cannot connect to this port over the internet, I would be very grateful.


Solution

  • You haven't forwarded the ports correctly. Nothing to do with the code.

    As @EJP has suggested, there doesn't seem to be anything wrong with my code. I have since hosted this server application using Amazon EC2, and it has worked flawlessly.

    There is an issue with the firmware of my router which is preventing port forwarding.