SoFunction
Updated on 2025-03-06

C# implements port mapping program in synchronization mode

Today I plan to write an FtpServer to play with it. I need to take a look at the commonly used command forms of ftp software (it is too troublesome to implement all ftp commands in full). At first, I planned to see how cuteftp accesses ftpserver by grabbing packets, but to save the commands in it, it has to be copied one by one. It is too troublesome, so I wrote a proxy program through proxy mode to get its interactive commands. After writing a simple port mapping program in synchronization mode, I found that it is much simpler than commonly used asynchronous proxy, so I posted this code for future query:

class Program
{
    static void Main(string[] args)
    {
        TcpListener listener = new TcpListener(new IPEndPoint(, 8000));
        ();
        while (true)
        {
            var client = ();

            ("connected");
            var proxy = new TcpClient();
            ("remote connected");
            (new IPEndPoint(, 21));

            new SyncProxy("client->remote",(), ());
            new SyncProxy("remote->client",(), ());
        }
    }
}

class SyncProxy
{
    NetworkStream read;
    NetworkStream write;
    string name;

    public SyncProxy(string name, NetworkStream read,NetworkStream write)
    {
         = name;
         = read;
         = write;

        (PipeStream);
    }

    void PipeStream(object state)
    {
        byte[] buffer = new byte[1500];
        int count = 0;
        while (true)
        {
            try
            {
                count = (buffer, 0, );
            }
            catch (Exception)
            {
                count = 0;
            }

            if (count == 0)
            {
                (name+" closed");
                ();
                break;
            }

            (name + ": "+ (buffer, 0, count));
            (buffer, 0, count);
        }
    }
}

The cuteFtp interactive command obtained through it is as follows:

connected
remote connected
client->remote: 220 Serv-U FTP Server v6.0 for WinSock ready...
remote->client: USER 1
client->remote: 331 User name okay, need password.
remote->client: PASS 1
client->remote: 230 User logged in, proceed.
remote->client: PWD
client->remote: 257 "/" is current directory.
remote->client: FEAT
client->remote: 211-Extension supported
client->remote: CLNT
MDTM
MDTM YYYYMMDDHHMMSS[+-TZ];filename
SIZE
SITE PSWD;EXEC;SET;INDEX;ZONE;CHMOD;MSG
REST STREAM
XCRC filename;start;end
MODE Z
211 End
remote->client: REST 0
client->remote: 350 Restarting at 0. Send STORE or RETRIEVE.
remote->client: PASV
client->remote: 227 Entering Passive Mode (127,0,0,1,29,18)
remote->client: LIST
client->remote: 150 Opening ASCII mode data connection for /bin/ls.
client->remote: 226 Transfer complete.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.