コード例 #1
0
        private protected override ArxOne.Ftp.FtpClient _getClient()
        {
            var client = new ArxOne.Ftp.FtpClient(this.Uri != null ? this.Uri : new Uri("ftp://" + this.Host), this.Credentials, new FtpClientParameters()
            {
                ConnectTimeout = TimeSpan.FromSeconds(60),
                ProxyConnect   = e =>
                {
                    var s = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                    {
                        ProxyEndPoint = new IPEndPoint(IPAddress.Parse(_config.IpAddress), _config.Port),
                        ProxyUser     = _config.UserName,
                        ProxyPass     = _config.Password,
                        ProxyType     = _config.Type
                    };

                    switch (e)
                    {
                    case DnsEndPoint dns:
                        s.Connect(dns.Host, dns.Port);
                        break;

                    case IPEndPoint ip:
                        s.Connect(ip);
                        break;

                    default: throw new NotSupportedException();
                    }

                    return(s);
                }
            });
コード例 #2
0
        /// <summary>
        /// 连接到服务器
        /// </summary>
        public bool Connect()
        {
            if (socket != null && socket.Connected)
            {
                return(true);
            }
            int retry = 0;

Connect:
            try
            {
                socket = GetSocket();
                socket.Connect(epServer);
                BeginDataReceive(this.socket);
                return(true);
            }
            catch (Exception e)
            {
                retry++;
                if (retry < 3)
                {
                    goto Connect;
                }
                policy.OnConnectServerError(e);
                return(false);
            }
        }
コード例 #3
0
        private SocksHttpWebResponse InternalGetResponse()
        {
            var response = new StringBuilder();

            using (var _socksConnection =
                       new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                var proxyUri  = Proxy.GetProxy(RequestUri);
                var ipAddress = GetProxyIpAddress(proxyUri);
                _socksConnection.ProxyEndPoint = new IPEndPoint(ipAddress, proxyUri.Port);
                _socksConnection.ProxyType     = ProxyTypes.Socks5;

                // open connection
                _socksConnection.Connect(RequestUri.Host, 80);
                // send an HTTP request
                _socksConnection.Send(Encoding.ASCII.GetBytes(RequestMessage));
                // read the HTTP reply
                var buffer = new byte[1024];

                var bytesReceived = _socksConnection.Receive(buffer);
                while (bytesReceived > 0)
                {
                    response.Append(Encoding.ASCII.GetString(buffer, 0, bytesReceived));
                    bytesReceived = _socksConnection.Receive(buffer);
                }
            }
            return(new SocksHttpWebResponse(response.ToString()));
        }
コード例 #4
0
        public void forwardFrame(IPFrame frame)
        {
            var id       = RandomString(10);
            var udpFrame = (UDPFrame)frame.EncapsulatedFrame;
            var e        = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("192.168.1.220"), udpFrame.DestinationPort);

            logger.Debug("{0} Source Port: {1}", id, udpFrame.SourcePort);
            logger.Debug("{0} Dest Port: {1}", id, udpFrame.DestinationPort);
            ProxySocket socket;
            var         cacheKey = string.Format("{0}:{1}->{2}", udpFrame.SourcePort, udpFrame.DestinationPort, e.ToString());

            if (!natTable.TryGetValue(cacheKey, out socket))
            {
                socket = new ProxySocket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                socket.ProxyEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("192.168.1.150"), 1080);
                socket.ProxyType     = ProxyTypes.Socks5;
                socket.Connect(e);
                Task.Run(() =>
                {
                    try
                    {
                        logger.Debug("{0} Create a new UDP Receive Task", id);
                        var buffer = new byte[8192];
                        ProxySocket tmp;
                        while (natTable.TryGetValue(cacheKey, out tmp))
                        {
                            logger.Debug("start receive");
                            var bytesReceived = socket.Receive(buffer);
                            logger.Debug("{0} Received packet", id);
                            natTable.Add(cacheKey, socket);
                            var receivedIPFrame                = new IPv4Frame();
                            receivedIPFrame.SourceAddress      = frame.DestinationAddress;
                            receivedIPFrame.DestinationAddress = frame.SourceAddress;
                            receivedIPFrame.Protocol           = IPProtocol.UDP;
                            var receivedUDPFrame               = new UDPFrame();
                            receivedUDPFrame.SourcePort        = udpFrame.DestinationPort;
                            receivedUDPFrame.DestinationPort   = udpFrame.SourcePort;
                            logger.Debug("{0} RSource Port: {1}", id, receivedUDPFrame.SourcePort);
                            logger.Debug("{0} RDest Port: {1}", id, receivedUDPFrame.DestinationPort);
                            receivedUDPFrame.EncapsulatedFrame = new RawDataFrame(buffer, 0, bytesReceived);
                            receivedIPFrame.EncapsulatedFrame  = receivedUDPFrame;
                            receivedUDPFrame.Checksum          = receivedUDPFrame.CalculateChecksum(receivedIPFrame.GetPseudoHeader());
                            tap.Write(receivedIPFrame.FrameBytes, 0, receivedIPFrame.Length);
                            tap.Flush();
                            logger.Debug("{0} wrote", id);
                        }
                    }
                    catch (SocketException err)
                    {
                        logger.Error(err);
                    }
                });
            }
            natTable.Add(cacheKey, socket);
            socket.BeginSend(udpFrame.EncapsulatedFrame.FrameBytes, 0, udpFrame.EncapsulatedFrame.FrameBytes.Length, 0, ar =>
            {
                socket.EndSend(ar);
                logger.Debug("{0} Sent to Dest", id);
            }, null);
        }
コード例 #5
0
        /// <summary>
        ///   Opens the connection to the XMPP server.
        /// </summary>
        private void Connect()
        {
            try
            {
                if (ConnectionString.ResolveHostName)
                {
                    // ReSharper disable RedundantBaseQualifier
                    base.ResolveHostName();
                    // ReSharper restore RedundantBaseQualifier
                }

                var hostadd      = Dns.GetHostEntry(HostName).AddressList[0];
                var hostEndPoint = new IPEndPoint(hostadd, ConnectionString.PortNumber);

                socket = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                if (ConnectionString.UseProxy)
                {
                    IPAddress proxyadd      = Dns.GetHostEntry(ConnectionString.ProxyServer).AddressList[0];
                    var       proxyEndPoint = new IPEndPoint(proxyadd, ConnectionString.ProxyPortNumber);

                    switch (ConnectionString.ProxyType)
                    {
                    case "SOCKS4":
                        socket.ProxyType = ProxyTypes.Socks4;
                        break;

                    case "SOCKS5":
                        socket.ProxyType = ProxyTypes.Socks5;
                        break;

                    default:
                        socket.ProxyType = ProxyTypes.None;
                        break;
                    }

                    socket.ProxyEndPoint = proxyEndPoint;
                    socket.ProxyUser     = ConnectionString.ProxyUserName;

                    if (!String.IsNullOrWhiteSpace(ConnectionString.ProxyPassword))
                    {
                        socket.ProxyPass = ConnectionString.ProxyPassword;
                    }
                }

                // Disables the Nagle algorithm for send coalescing.
                socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1);

                // Make the socket to connect to the Server
                socket.Connect(hostEndPoint);

                // Create the Stream Instance
                networkStream = new NetworkStream(socket, false);
            }
            catch (Exception ex)
            {
                throw new XmppException(
                          String.Format("Unable to connect to XMPP server {0}", ConnectionString.HostName), ex);
            }
        }
コード例 #6
0
    static void Main(string[] args)
    {
        // create a new ProxySocket
        ProxySocket s = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        // set the proxy settings
        s.ProxyEndPoint = new IPEndPoint(IPAddress.Parse("10.0.0.5"), 1080);
        s.ProxyUser     = "******";
        s.ProxyPass     = "******";
        s.ProxyType     = ProxyTypes.Socks5;            // if you set this to ProxyTypes.None,
        // the ProxySocket will act as a normal Socket
        // connect to the remote server
        // (note that the proxy server will resolve the domain name for us)
        s.Connect("www.mentalis.org", 80);
        // send an HTTP request
        s.Send(Encoding.ASCII.GetBytes("GET / HTTP/1.0\r\nHost: www.mentalis.org\r\n\r\n"));
        // read the HTTP reply
        int recv = 0;

        byte [] buffer = new byte[1024];
        recv = s.Receive(buffer);
        while (recv > 0)
        {
            Console.Write(Encoding.ASCII.GetString(buffer, 0, recv));
            recv = s.Receive(buffer);
        }
        // wait until the user presses enter
        Console.WriteLine("Press enter to continue...");
        Console.ReadLine();
    }
コード例 #7
0
        void btnTestProxy_Click(object sender, System.EventArgs e)
        {
            if (txtProxyIpAddress.Text.Trim() == "")
            {
                MsgBox.Warning("Sorry,the IP address can't be empty");
                return;
            }
            if (this.txtProxyUserName.Text.Trim() == "")
            {
                MsgBox.Warning("Sorry,the user name can't be empty");
                return;
            }
            if (this.txtProxyPortNumber.Text.Trim() == "")
            {
                MsgBox.Warning("Sorry,the port number can't be empty");
                return;
            }

            using (var cursor = new WaitCursor())
            {
                using (ProxySocket socket = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    IPEndPoint          endPoint      = new IPEndPoint(IPAddress.Parse(txtIpAddress.Text), Convert.ToInt32(txtPortNumber.Text));
                    IPEndPoint          proxyEndPoint = new IPEndPoint(IPAddress.Parse(this.txtProxyIpAddress.Text), Convert.ToInt32(this.txtProxyPortNumber.Text));
                    ProxyTypes          proxyType     = (ProxyTypes)Enum.Parse(typeof(ProxyTypes), ddlProxyType.SelectedItem.ToString());
                    TcpConnectionParams Params        = new TcpConnectionParams(endPoint, proxyEndPoint, proxyType, txtProxyUserName.Text, txtProxyPassword.Text);
                    socket.ProxyEndPoint = Params.ProxyEndPoint;
                    socket.ProxyType     = Params.ProxyType;
                    socket.ProxyUser     = Params.ProxyUser;
                    socket.ProxyPass     = Params.ProxyPassword;

                    try
                    {
                        socket.Connect(Params.EndPoint);
                        MsgBox.Warning("Test successful");
                    }
                    catch
                    {
                        MsgBox.Warning("Sorry,test failed,please try again");
                    }
                    finally
                    {
                        try
                        {
                            socket.Shutdown(SocketShutdown.Both);
                            socket.Close();
                        }
                        catch
                        {
                        }
                    }
                }
            }
        }
コード例 #8
0
        public void Process()
        {
            var localEndPoint  = (IPEndPoint)client.LocalEndPoint;
            var remoteEndPoint = (IPEndPoint)client.RemoteEndPoint;
            var connection     = connectionTracker[new Connection(ProtocolType.Tcp, localEndPoint, remoteEndPoint)].Mirror;

            if (connection != null)
            {
                var initialEndPoint   = connection.Source;
                var requestedEndPoint = connection.Destination;
                var tcpConnection     = connectionTracker.GetTCPConnection(initialEndPoint, requestedEndPoint);

                var logMessage = string.Format("{0}[{1}] {2} {{0}} connection to {3}",
                                               tcpConnection != null ? tcpConnection.ProcessName : "unknown",
                                               tcpConnection != null ? tcpConnection.PID : 0,
                                               initialEndPoint, requestedEndPoint);
                try
                {
                    var proxy = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    configureProxySocket(proxy, requestedEndPoint);

                    debug.Log(1, logMessage + " via {1}", "requested", proxy.ProxyEndPoint);

                    proxy.Connect(requestedEndPoint);

                    SocketPump.Pump(client, proxy);

                    proxy.Close();
                    debug.Log(1, logMessage, "closing");
                }
                catch (Exception ex)
                {
                    debug.Log(1, logMessage + ": {1}", "failed", ex.Message);
                }

                connectionTracker.QueueForCleanUp(connection);
            }
            else
            {
                var tcpConnection = connectionTracker.GetTCPConnection(remoteEndPoint, localEndPoint);
                debug.Log(1, "{0}[{1}] {2} has no mapping",
                          tcpConnection != null ? tcpConnection.ProcessName : "unknown",
                          tcpConnection != null ? tcpConnection.PID : 0,
                          remoteEndPoint);
                client.Send(Encoding.ASCII.GetBytes("No mapping\r\n"));
            }

            client.Close();
        }
コード例 #9
0
ファイル: Connection.cs プロジェクト: fossabot/PlayerIOClient
        public Connection(ServerEndpoint endpoint, string joinKey, MultiplayerProxy proxy = null)
        {
            _endpoint = endpoint;
            _joinKey  = joinKey;

            _socket = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            if (proxy != null)
            {
                _socket.ProxyEndPoint = new IPEndPoint(IPAddress.Parse(proxy.Address), proxy.Port);
                _socket.ProxyType     = proxy.Type;

                if (proxy.Username != null)
                {
                    _socket.ProxyUser = proxy.Username;
                }

                if (proxy.Password != null)
                {
                    _socket.ProxyPass = proxy.Password;
                }
            }

            // TODO: check for functional non-transparent proxy connection per MultiplayerProxy.StrictProxyMode
            _socket.Connect(endpoint.Address, endpoint.Port);

            _stream = new NetworkStream(_socket);

            _serializer   = new BinarySerializer();
            _deserializer = new BinaryDeserializer();

            _socket.Send(new[] { (byte)Enums.ProtocolType.Binary });
            _socket.Send(_serializer.Serialize(new Message("join", joinKey)));

            OnMessage += (sender, message) => {
                if (message.Type == "playerio.joinresult")
                {
                    if (!message.GetBoolean(0))
                    {
                        throw new PlayerIOError((ErrorCode)message.GetInteger(1), message.GetString(2));
                    }

                    this.Connected = true;
                }
            };

            _deserializer.OnDeserializedMessage += (message) => OnMessage.Invoke(this, message);
            _stream.BeginRead(_buffer, 0, _buffer.Length, new AsyncCallback(this.ReceiveCallback), null);
        }
コード例 #10
0
        private SocksHttpWebResponse InternalGetResponse()
        {
            var response = new StringBuilder();

            using (var _socksConnection =
                       new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                var proxyUri  = Proxy.GetProxy(RequestUri);
                var ipAddress = GetProxyIpAddress(proxyUri);
                _socksConnection.ProxyEndPoint = new IPEndPoint(ipAddress, proxyUri.Port);
                _socksConnection.ProxyType     = ProxyTypes.Socks5;



                // open connection
                _socksConnection.Connect(RequestUri.Host, 80);
                // send an HTTP request
                _socksConnection.Send(_correctEncoding.GetBytes(RequestMessage));
                // read the HTTP reply
                var buffer = new byte[1024];

                var bytesReceived = _socksConnection.Receive(buffer);
                while (bytesReceived > 0)
                {
                    string chunk     = _correctEncoding.GetString(buffer, 0, bytesReceived);
                    string encString = EncodingHelper.GetEncodingFromChunk(chunk);
                    if (!string.IsNullOrEmpty(encString))
                    {
                        try
                        {
                            _correctEncoding = Encoding.GetEncoding(encString);
                        }
                        catch
                        {
                            //TODO: do something here
                        }
                    }
                    response.Append(chunk);
                    bytesReceived = _socksConnection.Receive(buffer);
                }
            }
            return(new SocksHttpWebResponse(response.ToString(), _correctEncoding));
        }
コード例 #11
0
 public bool connect(string msg = "")
 {
     try
     {
         proxySocket_0.Connect(ipendPoint_0);
         if (!proxySocket_0.Connected)
         {
             return(false);
         }
         client.Client   = proxySocket_0;
         networkStream_0 = client.GetStream();
         return(true);
     }
     catch (Exception ex)
     {
         msg = ex.Message;
         return(false);
     }
 }
コード例 #12
0
 public void Connect()
 {
     try
     {
         proxySocket_0.Connect(ipendPoint_0);
         if (proxySocket_0.Connected)
         {
             tcpClient_0 = new TcpClient();
             tcpClient_0.ReceiveTimeout = 3000;
             tcpClient_0.Client         = proxySocket_0;
             networkStream_0            = tcpClient_0.GetStream();
             networkStream_0.BeginRead(byte_0, 0, byte_0.Length, method_0, networkStream_0);
             timer_3.Enabled = true;
             timer_3.Start();
             OnConnected onConnected = onConnected_0;
             if (onConnected != null)
             {
                 onConnected(true, false);
             }
         }
         else
         {
             OnConnected onConnected2 = onConnected_0;
             if (onConnected2 != null)
             {
                 onConnected2(false, false);
             }
         }
     }
     catch
     {
         OnConnected onConnected3 = onConnected_0;
         if (onConnected3 != null)
         {
             onConnected3(false, false);
         }
     }
 }
コード例 #13
0
        private SocksHttpWebResponse InternalGetResponse()
        {
            var response = new StringBuilder();

            using (var socksConnection = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                var webProxy = (WebProxy)Proxy;

                socksConnection.ProxyType     = ProxyType;
                socksConnection.ProxyUser     = ((NetworkCredential)webProxy.Credentials).UserName;
                socksConnection.ProxyPass     = ((NetworkCredential)webProxy.Credentials).Password;
                socksConnection.ProxyEndPoint = new IPEndPoint(Dns.GetHostAddresses(webProxy.Address.Host)[0],
                                                               webProxy.Address.Port);

                // open connection
                socksConnection.Connect(RequestUri.Host, 80);

                // send an HTTP request
                socksConnection.Send(Encoding.ASCII.GetBytes(RequestMessage));

                // read the HTTP reply
                var buffer = new byte[1024];

                var bytesReceived = socksConnection.Receive(buffer);
                if (bytesReceived == 0)
                {
                    throw new ProxyException(5);
                }

                while (bytesReceived > 0)
                {
                    response.Append(Encoding.ASCII.GetString(buffer, 0, bytesReceived));
                    bytesReceived = socksConnection.Receive(buffer);
                }
            }
            return(new SocksHttpWebResponse(response.ToString()));
        }
コード例 #14
0
        private SocksHttpWebResponse InternalGetResponse()
        {
            MemoryStream data   = null;
            string       header = string.Empty;

            using (var _socksConnection = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                var proxyUri  = Proxy.GetProxy(RequestUri);
                var ipAddress = GetProxyIpAddress(proxyUri);
                _socksConnection.ProxyEndPoint = new IPEndPoint(ipAddress, proxyUri.Port);
                _socksConnection.ProxyType     = ProxyTypes.Socks5;

                // open connection
                _socksConnection.Connect(RequestUri.Host, 80);

                // send an HTTP request
                _socksConnection.Send(Encoding.UTF8.GetBytes(RequestMessage));

                // read the HTTP reply
                var  buffer        = new byte[1024 * 4];
                int  bytesReceived = 0;
                bool headerDone    = false;

                while ((bytesReceived = _socksConnection.Receive(buffer)) > 0)
                {
                    if (!headerDone)
                    {
                        var headPart = Encoding.UTF8.GetString(buffer, 0, bytesReceived > 1024 ? 1024 : bytesReceived);
                        var indexOfFirstBlankLine = headPart.IndexOf("\r\n\r\n");
                        if (indexOfFirstBlankLine > 0)
                        {
                            headPart   = headPart.Substring(0, indexOfFirstBlankLine);
                            header    += headPart;
                            headerDone = true;

                            var headerPartLength = Encoding.UTF8.GetByteCount(headPart) + 4;

                            // 0123456789
                            //   ----
                            if (headerPartLength < bytesReceived)
                            {
                                data = new MemoryStream();
                                data.Write(buffer, headerPartLength, bytesReceived - headerPartLength);
                            }
                        }
                        else
                        {
                            header += headPart;
                        }
                    }
                    else
                    {
                        if (data == null)
                        {
                            data = new MemoryStream();
                        }
                        data.Write(buffer, 0, bytesReceived);
                    }
                }

                if (data != null)
                {
                    data.Position = 0;
                }
            }

            return(new SocksHttpWebResponse(data, header));
        }
コード例 #15
0
        private void button1_Click_001(object sender, EventArgs e)
        {
            //https://github.com/poma/ProxySocket
            textBox1.Text = string.Empty;
            foreach (var proxyAddress in tbProxies.Lines)
            {
                try
                {
                    var ipport   = proxyAddress.Split(':');
                    var ipString = ipport[0];
                    var port     = int.Parse(ipport[1]);

                    // create a new ProxySocket
                    ProxySocket socket = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    // set the proxy settings
                    socket.ProxyEndPoint = new IPEndPoint(IPAddress.Parse(ipString), port);
                    //s.ProxyUser = "******";
                    //s.ProxyPass = "******";
                    socket.SendTimeout = 2000;
                    socket.ProxyType   = ProxyTypes.Https;  // if you set this to ProxyTypes.None,
                                                            // the ProxySocket will act as a normal Socket
                                                            // connect to the remote server
                                                            // (note that the proxy server will resolve the domain name for us)

                    var uri  = new Uri("https://httpbin.org/ip");
                    var host = uri.Host;
                    var path = uri.AbsolutePath;
                    socket.Connect(host, 443);
                    //SslStream tls = new SslStream(new NetworkStream(socket));
                    //tls.AuthenticateAsClient(host);
                    var request = $"GET {path} HTTP/1.0{nl}Host: {host}{nl}{nl}";

                    //tls.Write(Encoding.ASCII.GetBytes(request));
                    //using (var sr = new StreamReader(tls, Encoding.UTF8))
                    //{
                    //    string response = sr.ReadToEnd();
                    //    textBox1.Text += response;
                    //}
                    //return;

                    // send an HTTP request
                    socket.Send(Encoding.ASCII.GetBytes(request));
                    // read the HTTP reply
                    int    recv   = 0;
                    byte[] buffer = new byte[1024];
                    recv = socket.Receive(buffer);
                    StringBuilder stringBuilder = new StringBuilder();
                    while (recv > 0)
                    {
                        stringBuilder.Append(Encoding.ASCII.GetString(buffer, 0, recv));
                        recv = socket.Receive(buffer);
                    }
                    textBox1.Text += stringBuilder.ToString();
                    //string page = client.Get("https://httpbin.org/get");
                    //http://check-host.net/ip
                }
                catch (Exception exception)
                {
                    textBox1.Text = $"{exception}";
                }
            }
        }
コード例 #16
0
ファイル: ProxyTester.cs プロジェクト: kmataru/bean-cannon
        private bool ProbeProxySocketImplementation(
            ProxyDatum proxy,
            SocketType socketType, ProtocolType protocolType, ProxyTypes proxyType,
            out AddressFamily addressFamily,
            out string errorMsg, out TimeSpan connectionSeconds
            )
        {
            Stopwatch stopWatch = new Stopwatch();

            addressFamily     = AddressFamily.Unspecified;
            errorMsg          = "";
            connectionSeconds = InvalidProxyConnectionTime;

            try
            {
                //stopWatch.Start();

                byte[] recvBuf = new byte[128];

                // TODO: Get IP from DNS
                IPEndPoint RHost = new IPEndPoint(IPAddress.Parse("104.20.2.47"), 80);
                addressFamily = RHost.AddressFamily;

                using (ProxySocket proxySocket = new ProxySocket(RHost.AddressFamily, socketType, protocolType))
                {
                    proxySocket.ProxyEndPoint = new IPEndPoint(IPAddress.Parse(proxy.Ip), proxy.Port);
                    proxySocket.ProxyType     = proxyType;

                    proxySocket.NoDelay = true;

                    stopWatch.Start();

                    try
                    {
                        proxySocket.Connect(RHost);
                    }
                    catch (SocketException) { return(false); }

                    proxySocket.Blocking = false;

                    try
                    {
                        proxySocket.Send(probeProxyHeaderBuffer, SocketFlags.None);

                        // TODO : Review

                        /*
                         * if (!proxySocket.Poll((int)connectionSeconds.TotalMilliseconds * 1000, SelectMode.SelectRead))
                         * {
                         *      return false;
                         * }
                         * //*/
                        /*
                         * if (proxySocket.Blocking)
                         * {
                         *      proxySocket.ReceiveTimeout = 10000;
                         *      proxySocket.Receive(recvBuf, recvBuf.Length, SocketFlags.None);
                         * }
                         * //*/
                    }
                    catch (SocketException) { return(false); }
                }

                return(true);
            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;
                return(false);
            }
            finally
            {
                stopWatch.Stop();
                connectionSeconds = stopWatch.Elapsed;
            }
        }
コード例 #17
0
    static void Main(string[] args)
    {
        {
            // create a new ProxySocket
            ProxySocket s = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            // set the proxy settings
            //s.ProxyEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9150);
            //s.ProxyUser = "******";
            //s.ProxyPass = "******";
            s.ProxyType = ProxyTypes.None;    // if you set this to ProxyTypes.None,
                                              // the ProxySocket will act as a normal Socket

            // http://www.whatsmyip.org/

            //<!-- Please DO NOT use our site to power an IP bot, script or other automated IP-lookup software! - for humans only! -->
            //<h1>Your IP Address is <span id="ip">169.120.138.139</span></h1>

            // connect to the remote server
            // (note that the proxy server will resolve the domain name for us)
            s.Connect("torguard.net", 80);
            // send an HTTP request
            s.Send(Encoding.ASCII.GetBytes("GET /whats-my-ip.php HTTP/1.0\r\nHost: torguard.net\r\n\r\n"));
            // read the HTTP reply
            int    recv   = 0;
            byte[] buffer = new byte[8096];
            recv = s.Receive(buffer);
            while (recv > 0)
            {
                Console.Write(Encoding.ASCII.GetString(buffer, 0, recv));
                recv = s.Receive(buffer);
            }
        }

        {
            // create a new ProxySocket
            ProxySocket s = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            // set the proxy settings
            s.ProxyEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9150);
            //s.ProxyUser = "******";
            //s.ProxyPass = "******";
            s.ProxyType = ProxyTypes.Socks5;    // if you set this to ProxyTypes.None,
                                                // the ProxySocket will act as a normal Socket

            // http://www.whatsmyip.org/

            //<!-- Please DO NOT use our site to power an IP bot, script or other automated IP-lookup software! - for humans only! -->
            //<h1>Your IP Address is <span id="ip">169.120.138.139</span></h1>

            // connect to the remote server
            // (note that the proxy server will resolve the domain name for us)
            s.Connect("torguard.net", 80);
            // send an HTTP request
            s.Send(Encoding.ASCII.GetBytes("GET /whats-my-ip.php HTTP/1.0\r\nHost: torguard.net\r\n\r\n"));
            // read the HTTP reply
            int    recv   = 0;
            byte[] buffer = new byte[1024];
            recv = s.Receive(buffer);
            while (recv > 0)
            {
                Console.Write(Encoding.ASCII.GetString(buffer, 0, recv));
                recv = s.Receive(buffer);
            }
        }

        // wait until the user presses enter
        Console.WriteLine("Press enter to continue...");
        Console.ReadLine();
    }