HTTP proxy support in .NET does not actually support the lower level classes like TcpClient or Socket. But I want to connect a TCPServer (ip, port) through HTTP proxy that s
We have managed to implement it using .Net's Socket. Nuget package is called Filemail.ProxiedTcpClient. The code is pretty simple:
public static TcpClient CreateProxied(Uri proxy, Uri destination)
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(proxy.Host, proxy.Port);
var connectMessage = Encoding.UTF8.GetBytes($"CONNECT {destination.Host}:{destination.Port} HTTP/1.1{Environment.NewLine}{Environment.NewLine}");
socket.Send(connectMessage);
byte[] receiveBuffer = new byte[1024];
var received = socket.Receive(receiveBuffer);
var response = ASCIIEncoding.ASCII.GetString(receiveBuffer, 0, received);
if (!response.Contains("200 OK"))
{
throw new Exception($"Error connecting to proxy server {destination.Host}:{destination.Port}. Response: {response}");
}
return new TcpClient
{
Client = socket
};
}
Contribute here: https://github.com/filemail/ProxiedTcpClient