使用Socks5代理服务器连接网络

本文介绍了一种通过Socks5代理服务器实现网络连接的方法。文章详细解释了如何配置代理服务器的身份验证,并提供了完整的示例代码,展示了如何建立连接、发送请求及接收响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    /// <summary>
    /// 使用Socks5代理服务器连接网络
    /// </summary>
    class SockProxy
    {
        bool m_RequireAuthorize = false;
        string m_user = string.Empty;
        string m_pass = string.Empty;

        /// <summary>
        /// default is false
        /// </summary>
        public bool RequireAuthorize
        {
            get { return m_RequireAuthorize; }
            set { m_RequireAuthorize = value; }
        }
        public string Username
        {
            get { return m_pass; }
            set { m_pass = value; }
        }
        public string Password
        {
            get { return m_user; }
            set { m_user = value; }
        }

        public bool ConnectProxyServer(string strRemoteHost, int iRemotePort, Socket sProxyServer)
        {
            //构造Socks5代理服务器第一连接头(无用户名密码)
            byte[] bySock5Send = new Byte[10];
            bySock5Send[0] = 5;
            bySock5Send[1] = 1;
            bySock5Send[2] = RequireAuthorize ? (byte)2 : (byte)0;

            //发送Socks5代理第一次连接信息
            sProxyServer.Send(bySock5Send, 3, SocketFlags.None);

            byte[] bySock5Receive = new byte[10];
            int iRecCount = sProxyServer.Receive(bySock5Receive, bySock5Receive.Length, SocketFlags.None);


            //用户验证
            if (bySock5Receive[1] == 2 && !RequireAuthorize)
            {
                throw new Exception("代理服务器需要进行身份确认。");
            }
            else if (bySock5Receive[1] == 2)
            {
                //构造Socks5代理服务器第一连接头(无用户名密码)
                byte[] bUser = Encoding.Default.GetBytes(Username);
                byte[] bPass = Encoding.Default.GetBytes(Password);

                int dl = 3 + bUser.Length + bPass.Length;

                bySock5Send = new Byte[dl];
                bySock5Send[0] = 5;
                bySock5Send[1] = (byte)bUser.Length;
                Array.Copy(bUser, 0, bySock5Send, 2, bUser.Length);
                bySock5Send[2 + bUser.Length] = (byte)bPass.Length;
                Array.Copy(bPass, 0, bySock5Send, 3 + bUser.Length, bPass.Length);

                //发送Socks5代理第一次连接信息
                sProxyServer.Send(bySock5Send, dl, SocketFlags.None);

                bySock5Receive = new byte[100];
                iRecCount = sProxyServer.Receive(bySock5Receive, bySock5Receive.Length, SocketFlags.None);
            }

            if (iRecCount < 2)
            {
                sProxyServer.Close();
                throw new Exception("不能获得代理服务器正确响应。");
            }

            if (bySock5Receive[0] != 5 || (bySock5Receive[1] != 0 && bySock5Receive[1] != 2))
            {
                sProxyServer.Close();
                throw new Exception("代理服务其返回的响应错误。");
            }

            if (bySock5Receive[1] == 0)
            {
                bySock5Send[0] = 5;
                bySock5Send[1] = 1;
                bySock5Send[2] = 0;
                bySock5Send[3] = 1;

                IPAddress ipAdd = Dns.Resolve(strRemoteHost).AddressList[0];
                string strIp = ipAdd.ToString();
                string[] strAryTemp = strIp.Split(new char[] { '.' });
                bySock5Send[4] = Convert.ToByte(strAryTemp[0]);
                bySock5Send[5] = Convert.ToByte(strAryTemp[1]);
                bySock5Send[6] = Convert.ToByte(strAryTemp[2]);
                bySock5Send[7] = Convert.ToByte(strAryTemp[3]);

                bySock5Send[8] = (byte)(iRemotePort / 256);
                bySock5Send[9] = (byte)(iRemotePort % 256);

                sProxyServer.Send(bySock5Send, bySock5Send.Length, SocketFlags.None);
                iRecCount = sProxyServer.Receive(bySock5Receive, bySock5Receive.Length, SocketFlags.None);

                if (bySock5Receive[0] != 5 || bySock5Receive[1] != 0)
                {
                    sProxyServer.Close();
                    throw new Exception("第二次连接Socks5代理返回数据出错。");
                }
                return true;
            }

            else
            {
                if (bySock5Receive[1] == 2)
                    throw new Exception("代理服务器需要进行身份确认。");
                else
                    return false;
            }
            return false;
        }

        public Socket GetSocket(string strIpAdd, int iPort)
        {
            IPAddress hostadd = IPAddress.Parse(strIpAdd);//Dns.Resolve(strIpAdd).AddressList[0];
            IPEndPoint EPhost = new IPEndPoint(hostadd, iPort);
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            s.Connect(EPhost);
            return s;
        }
    }
//用法示例:

        private void Form1_Load(object sender, EventArgs e)
        {
            string proxyHost = "10.32.32.51";// "10.4.8.1";//
            int proxyProt = 1080;

            byte[] b;
            int rl = 0;
            string sr;

            SockProxy p = new SockProxy();

            {//如果不需要密码验证,略去这段代码
                p.RequireAuthorize = true;
                p.Username = "jerry";
                p.Password = "456321";
            }
            Socket sRH = p.GetSocket(proxyHost, proxyProt);

            p.ConnectProxyServer("10.32.9.16", 9160, sRH);
            b = Encoding.Default.GetBytes("GET /WAP/Default.aspx HTTP/1.0");
            sRH.Send(b);
            b = new byte[4096];
            rl = sRH.Receive(b);
            sr = Encoding.Default.GetString(b, 0, rl);
            MessageBox.Show(sr);
        }

 
About Cntlm proxy Cntlm (user-friendly wiki / technical manual) is an NTLM / NTLM Session Response / NTLMv2 authenticating HTTP proxy intended to help you break free from the chains of Microsoft proprietary world. You can use a free OS and honor our noble idea, but you can't hide. Once you're behind those cold steel bars of a corporate proxy server requiring NTLM authentication, you're done with. The same even applies to 3rd party Windows applications, which don't support NTLM natively. Here comes Cntlm. It stands between your applications and the corporate proxy, adding NTLM authentication on-the-fly. You can specify several "parent" proxies and Cntlm will try one after another until one works. All auth'd connections are cached and reused to achieve high efficiency. Just point your apps proxy settings at Cntlm, fill in cntlm.conf (cntlm.ini) and you're ready to do. This is useful on Windows, but essential for non-Microsoft OS's. Cntlm integrates TCP/IP port forwarding (HTTP tunneling), SOCKS5 proxy mode, standalone proxy allowing you to browse intranet as well as Internet and to access corporate web servers with NTLM protection. There are many advanced features like NTLMv2 support, password protection, password hashing, completely mutliplatform code (running on just about every architecture and OS out there) and so much more. Cntlm eats up so little resources it can be used on embedded platforms as well - it's written in plain C without any external dependencies. Cntlm has been tested against various ISA servers, WinGate, NetCache, Squid and Tinyproxy with and without NTLM auth. Memory management audits and profiling are inherent part of the development process. Each change in the code is audited using Valgrind, which acts as a virtual CPU and checks behaviour of each instruction of the application being profiled. Using this marvelous tool, you can uncloak any imbalance in malloc/free calls (double free's or leaks), operations with uninitialized memory, access outside of properly allocated memory and oh so much more.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值