public static void ProcessClient(Socket client) { var hostname = ""; var port = 80; try { /// Check client for data to be read if (!client.Poll(50000, SelectMode.SelectRead)) { return; } /// Read data using (var packetData = new MemoryStream()) { client.ReadToStream(packetData); if (packetData.Length == 0) { return; } /// Analyze received data string packetText = Encoding.ASCII.GetString(packetData.ToArray()); if (packetText.IndexOf("CONNECT") != 0) { Regex regex = new Regex("Host: (.*)\r\n", RegexOptions.IgnoreCase); if (regex.Match(packetText).Success) { hostname = regex.Match(packetText).Groups[1].Value; } } else { Regex regex = new Regex("CONNECT (.*):(.*) HTTP", RegexOptions.IgnoreCase); if (regex.Match(packetText).Success) { hostname = regex.Match(packetText).Groups[1].Value; port = Convert.ToInt32(regex.Match(packetText).Groups[2].Value); } } if (hostname.Length == 0) { return; } /// Connect to the server using (var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { server.Connect(hostname, port); if (!server.Connected) { return; } if (packetText.IndexOf("CONNECT") != 0) { /// Send initial packet to server server.Write(packetData); } else { /// Send "200 Connection Established" to client client.Write(Encoding.ASCII.GetBytes("HTTP/1.1 200 Connection Established\r\n\r\n")); } /// Simple tunneling while (client.Connected && server.Connected) { bool exchanged = false; /// Client -> Server exchange if (client.Poll(1000, SelectMode.SelectRead)) { using (var data = new MemoryStream()) { client.ReadToStream(data); if (data.Length != 0) { server.Write(data); exchanged = true; } } } /// Server -> Client exchange if (server.Poll(1000, SelectMode.SelectRead)) { using (var data = new MemoryStream()) { server.ReadToStream(data); if (data.Length != 0) { client.Write(data); exchanged = true; } } } /// If both sockets was not used sleep for 50 ms if (!exchanged) { Thread.Sleep(50); } } } } } catch (ObjectDisposedException) { } catch (IOException) { } catch (InvalidOperationException) { } catch (SocketException) { Console.WriteLine("Connection was closed by {0}.", hostname); } catch (NotSupportedException) { Console.WriteLine("Method is not supported by socket connected to {0}.", hostname); } catch (SecurityException) { Console.WriteLine("You have no privileges to execute this command."); } }