gpt4 book ai didi

c# - 如何将代理与 TcpClient.ConnectAsync() 一起使用?

转载 作者:行者123 更新时间:2023-12-02 10:45:24 25 4
gpt4 key购买 nike

.NET 中的 HTTP 代理支持实际上并不支持 TcpClient 或 Socket 等较低级别的类。但我想通过支持“CONNECT”命令的 HTTP 代理连接 TCPServer(ip、端口)。

所以我需要执行以下步骤:

  1. 连接到代理。
  2. 发送 CONNECT Host:Port HTTP/1.1<CR><LF>
  3. 发送 <CR><LF>
  4. 等待一行回复。如果包含HTTP/1.X 200 ,连接成功。
  5. 继续阅读响应行,直到收到空行。
  6. 它通过代理连接到外部世界。尽可能与代理进行任何数据交换。

实际上我在没有代理的情况下执行此操作

    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;
}

在连接 TcpClient 之前如何使用代理和凭据?

最佳答案

我找到了基于 .NET: Connecting a TcpClient through an HTTP proxy with authentication 的解决方案和 Bypass the proxy using 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;
}

关于c# - 如何将代理与 TcpClient.ConnectAsync() 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35066981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com