I've decided to roll my own FTP Socket client in C# in order to have more control but mostly for the learning experience. But I cannot figure out how much file data I need to read after issuing the RETR command. I am able to establish the initial FTP communication connection, and then connect a second socket on a new port by issuing the PASV command and all that good stuff.
My problem is, when I issue the RETR command on the Communication port, the FTP server begins sending the file over the Passive port and then issues the 226 command when it finishes sending on the Communication port. I can receive the data fine but sometimes the 226 command arrives on the Communication port before all of the file data arrives on the Passive port. So, if I immediately signal my Passive socket task to stop reading after I get the 226 command, it will sometimes miss out on the data that comprises the end of the file. I've tried checking for Socket.Available before exiting out of my Socket.Receive loop but more often than not Socket.Available will report 0 bytes available on the socket but with sockets that doesn't mean there isn't more data on the way. Reading the FTP spec it seems as though the FTP server is supposed to shut down the data connection after it finishes sending all the data but I don't think that is happening. I can keep looping reading 0 bytes of data all day long. Am I looking at a broken FTP server or am I doing something wrong in my methodology?
Now for some additional info that might be the answer to my question. Using Filezilla, connected to the same FTP server, I see that when requesting a file the FTP server appends the file length to the 150 command in parenthesis. For example, "150 Opening BINARY mode data connection for test.zip (123421 bytes)." Is this text part of the FTP standard? If all FTP servers use this same behavior and formatting then I can just keep reading until I hit 123,421 bytes. But if this isn't common behavior then I'm back at square one. Appreciate any ideas.