Federico Ponzi Federico Ponzi - 1 year ago 83
C Question

FTP implementation: close data socket every time

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
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?


Answer Source

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.

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