// Creates a data connection using the given command socket, mode, and message from the client giving the port public DataSocket(FTPSocket ftp, bool passive, string message) { if (passive) { // Establishes a server for the client to connect to in passive mode listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listener.Bind(new IPEndPoint(ftp.LocalIP, 0)); listener.Listen(1); var local = (IPEndPoint)listener.LocalEndPoint; var ip = local.Address.ToString().Replace('.', ','); var port = local.Port; ftp.Write("227 Entering Passive Mode ({0},{1},{2}).", ip, port / 256, port % 256); } else { // Connects to the clients data connection in active mode var match = Regex.Match(message, @"(\d+,\d+,\d+,\d+),(\d+),(\d+)"); address = IPAddress.Parse(match.Groups[1].Value.Replace(',', '.')); port = int.Parse(match.Groups[2].Value) * 256 + int.Parse(match.Groups[3].Value); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ftp.Write("200 PORT command successful. Consider using PASV."); } }
// Listens for commands from client on a loop public void Run() { Console.WriteLine("New connection"); // Create a wrapped socekt for sending and receivng using (ftp = new FTPSocket(_socket)) { try { // Run until something goes wrong or the quit command is received var stop = false; while (!stop) { stop = HandleCommand(); } } catch { Console.WriteLine("Unexpect error occured"); } } Console.WriteLine("Connection closed"); }