繫結至 TCP 網路連接埠

藉由 Socket 監聽,遠端啟動特定的執行檔案。

 

藉由 Socket 監聽,遠端啟動特定的執行檔案。

Source Code:

using System;
using System.Net.Sockets;
using System.Net;
using System.Linq;
using System.IO;
using System.Text;
using System.Diagnostics;

class TCP
{
    public static void Main(string[] args)
    {

        int port = int.TryParse(args[0], out port) ? port : 10000;

        TcpListener listener = new TcpListener(IPAddress.Any, port);

        while (true)
        {
            try
            {
                listener.Start();
            }
            catch
            {
                return;
            }

            using (Socket socket = listener.AcceptSocket())
            {
                using (NetworkStream stream = new NetworkStream(socket))
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        while (true)
                        {
                            string command = reader.ReadLine();

                            if (string.IsNullOrEmpty(command))
                            {
                                reader.Close();
                                stream.Close();

                                listener.Stop();

                                return;
                            }

                            if (string.IsNullOrWhiteSpace(command))
                            {
                                continue;
                            }



                            string[] split = command.Trim().Split(' ');

                            string filename = split.First();
                            string arg = string.Join(" ", split.Skip(1));

                            try
                            {
                                Process process = new Process();

                                process.StartInfo = new ProcessStartInfo();
                                process.StartInfo.FileName = filename;
                                process.StartInfo.Arguments = arg;
                                process.StartInfo.UseShellExecute = false;
                                process.StartInfo.RedirectStandardOutput = true;

                                process.Start();
                                process.StandardOutput.BaseStream.CopyTo(stream);
                                process.WaitForExit();
                            }
                            catch (Exception e)
                            {
                                string error = command + ":\n" + e.ToString();

                                byte[] buffer = Encoding.ASCII.GetBytes(error);
                                stream.Write(buffer, 0, buffer.Length);
                            }
                        }
                    }
                }
            }
        }
    }
}