3

如何将 proxy/socks4/socks5 添加到 C# Socket。

我需要使用它抛出 Socket。我不想使用 WebRequest 和任何类。

private static Socket ConnectSocket(string server, int port)
{
    Socket s = null;
    IPHostEntry hostEntry = null;

    // Get host related information.
    hostEntry = Dns.GetHostEntry(server);

    // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
    // an exception that occurs when the host IP Address is not compatible with the address family
    // (typical in the IPv6 case).
    foreach (IPAddress address in hostEntry.AddressList)
    {
        IPEndPoint ipe = new IPEndPoint(address, port);
        Socket tempSocket =
            new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

        tempSocket.Connect(ipe);

        if (tempSocket.Connected)
        {
            s = tempSocket;
            break;
        }
        else
        {
            continue;
        }
    }
    return s;
}

public static string SocketQuery(string Url, int Port, string Method = "GET", string Cookie = "", string DataFields = "")
{
    string host = ExtractDomainAndPathFromURL(Url);

    string request = Method.ToUpper() + " " + ExtractDomainAndPathFromURL(Url, 2) + " HTTP/1.1\r\n" +
        "Host: " + host + "\r\n" +
        ((Cookie != String.Empty) ? "Cookie: " + Cookie + "\r\n" : "") +
        ((Method.ToUpper() == "POST") ? "Content-Length:" + DataFields.Length + "\r\n" : "") +
        "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13\r\n" +
        "Connection: Close\r\n" +
        "Content-Type: application/x-www-form-urlencoded\r\n" +
        "\r\n" +
        ((Method.ToUpper() == "POST") ? DataFields : "");

    Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
    Byte[] bytesReceived = new Byte[256];

    Socket s = ConnectSocket(host, Port);

    if (s == null)
        return ("Connection failed");

    s.Send(bytesSent, bytesSent.Length, 0);

    int bytes = 0;
    string page = String.Empty;

    do
    {
        bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);
        page = page + Encoding.GetEncoding("UTF-8").GetString(bytesReceived, 0, bytes);
    }
    while (bytes > 0);

    return page;
}

我将在此代码中添加什么?

4

2 回答 2

3

当您清楚地创建一个 http Web 请求时,不太清楚为什么您说您不想使用WebRequest(或者我想,WebClient就此而言),但我假设您有您的理由!

简而言之,.Net 中没有支持 SOCKS 代理的内置方式,并且不支持低至套接字级别的 http 代理(因为无法保证请求是这样低的,所以没有任何意义http请求)。HttpWebRequest.Net 的较高层/层内置了 http 代理支持WebClient- 但你已经打折了。

我认为你的选择是:

  • 为工作使用正确的工具(HttpWebRequestWebClient)并免费获得 http 代理支持。
  • 使用 SOCKS 支持的第三方实现,如果您进行谷歌搜索,其中似乎有一些。(例如这个)。
于 2011-03-15T00:42:25.513 回答
2

而不是打开到实际位置的套接字,而是尝试打开到代理的套接字。

于 2011-03-15T05:14:44.650 回答