Question

I am implementing the TFTP (trivial FTP) protocol in Java. I have a client and a server, and so far the client can request a file and the server sends him that data.

Here is where I hit my problem - for obvious testing reasons, I run both the client and the server on my machine. However, when sending a file, there have to be two sockets listening on the same port:

  • the client needs to listen for received data packages
  • the server needs to listen for the client's acknowledgements

...and also two respective sockets for sending data and acknowledgements, also sharing a port.

This normally does happen on the same port, but on different machines. Is there a way to get around this, and make both client and server work peacefully on the same host, without any ugly hacks? And by ugly hacks I mean something like:

  • predefined offset for the ACK communication port (such as +15 over the data port; this is what I'm currently using now. It sort of works but it feels wrong and is error-prone)
  • repeatedly closing and opening sockets (send data, close socket used to send data so that the client can use that port to send his ACK, etc.); this also works at the moment, but also via a hack. Here is, for example, how I "reopen" a socket used for sending things:

    public void open() {
        try {
            socket = new DatagramSocket(localPortCache);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
    

This is evil. My sockets, originally, receive dynamically-allocated ephemeral port numbers. I then memorize that value and use it to "restore" my socket to the old port. However, it can't be guaranteed that that port is still available. It usually is, but there's no guarantee. Am I being overly-paranoid in this case?

  • generating a new ACK-communication port in the handshake and send it to the client via the control port (69) in an additional step

Update:

I have managed to fix my problem. My issue was that I wasn't trying to reuse my sockets. For instance, I sent something from a socket on port X, but then tried to allocate a new socket on that port to listen for the ACK, instead of just reusing the old socket.

Was it helpful?

Solution

The client doesn't need to use a fixed port number. Just bind it to zero. The server should send the response back to the originating client whatever its port number.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top