LeM*_*sel 2 .net c# proxy networking tcpclient
.NET中的HTTP代理支持实际上并不支持较低级别的类,例如TcpClient或Socket。但我想通过支持“ CONNECT”命令的HTTP代理连接TCPServer(IP,端口)。
因此,我需要执行以下步骤:
CONNECT Host:Port HTTP/1.1<CR><LF>
<CR><LF>
HTTP/1.X 200
,则连接成功。其实我没有代理就这样做
TcpClient _client;
NetworkStream _stream;
public static async Task<bool> ConnectAsync(string hostname, int port)
{
_client = new TcpClient();
await _client.ConnectAsync(hostname, port).ConfigureAwait(false);
_stream = conn._client.GetStream();
..... Do some stuff
// Connexion OK
return true;
}
Run Code Online (Sandbox Code Playgroud)
在连接TcpClient之前如何使用代理和凭据?
我发现基于.NET的解决方案:通过具有身份验证的HTTP代理连接TcpClient并使用TcpClient绕过代理
TcpClient _client;
NetworkStream _stream;
public TcpClient ProxyTcpClient(string targetHost, int targetPort, string httpProxyHost, int httpProxyPort, string proxyUserName, string proxyPassword)
{
const BindingFlags Flags = BindingFlags.NonPublic | BindingFlags.Instance;
Uri proxyUri = new UriBuilder
{
Scheme = Uri.UriSchemeHttp,
Host = httpProxyHost,
Port = httpProxyPort
}.Uri;
Uri targetUri = new UriBuilder
{
Scheme = Uri.UriSchemeHttp,
Host = targetHost,
Port = targetPort
}.Uri;
WebProxy webProxy = new WebProxy(proxyUri, true);
webProxy.Credentials = new NetworkCredential(proxyUserName, proxyPassword);
WebRequest request = WebRequest.Create(targetUri);
request.Proxy = webProxy;
request.Method = "CONNECT";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
Type responseType = responseStream.GetType();
PropertyInfo connectionProperty = responseType.GetProperty("Connection", Flags);
var connection = connectionProperty.GetValue(responseStream, null);
Type connectionType = connection.GetType();
PropertyInfo networkStreamProperty = connectionType.GetProperty("NetworkStream", Flags);
NetworkStream networkStream = (NetworkStream)networkStreamProperty.GetValue(connection, null);
Type nsType = networkStream.GetType();
PropertyInfo socketProperty = nsType.GetProperty("Socket", Flags);
Socket socket = (Socket)socketProperty.GetValue(networkStream, null);
return new TcpClient { Client = socket };
}
public static async Task<bool> ConnectAsync(string hostname, int port)
{
_client = ProxyTcpClient("IPTargetHost", 1234, "IPProxyHost", 5678, "Userproxy", "Userppwd");
_stream = conn._client.GetStream();
..... Do some stuff
// Connexion OK
return true;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3510 次 |
最近记录: |