0
votes

I'm implementing in c a sort of FTP protocol.

I' ve a server running. I start the client, connect to the server, and then send a GET file.txt request. The client parse the command, see it's a GET command and starts a server socket. The server recieves the command, and starts the data connection with the client and start sending file.txt on this connection.

When the server sent the file, it closes the client socket (Data).

When i want to GET another file, the port is already in use. How can i prevent this? Should i keep the data-connection open for all the command-connection session? In this case, how can my client know when the file is over?

Thanks

3

3 Answers

3
votes

When a socket is closed, it enters the TIME WAIT state (see here for the possible TCP states) and no other socket can be bound to the same address/port pair until the socket leaves TIME WAIT and is in the CLOSED state.

You can go around this by setting the SO_REUSEADDR socket option, that will allow two sockets to be bound to the same address if one of the sockets is in the TIME WAIT state.

1
votes

you need to open socket for transfer each time as the server will close it when transfer finish. you will know that the file is downloaded/uploaded by reading response from FTP Server for status code (226 or 250) - check List of FTP server return codes: https://en.wikipedia.org/wiki/List_of_FTP_server_return_codes

-1
votes

In my project, I use apache-commons-net, just keep the command connection alive with heartbeat command, and enter local passive mode every time to do file tranfer. The principle is same for your situation, I suggest send EPSV command before GETTING a file.txt.

refer: https://commons.apache.org/proper/commons-net/