Exemple #1
0
        /// <summary>
        /// 获取客户端IP
        /// </summary>
        /// <param name="context">HttpContext</param>
        /// <returns>ClientIP</returns>
        public static string GetClientIP(HttpContext context)
        {
            // 通过服务端转发的真实客户端IP
            string ip = context.Request.Headers["clientIp"];

            if (string.IsNullOrEmpty(ip) || string.Equals("unknown", ip, StringComparison.OrdinalIgnoreCase))
            {
                ip = context.Request.Headers["x-forwarded-for"];
            }

            if (string.IsNullOrEmpty(ip) || string.Equals("unknown", ip, StringComparison.OrdinalIgnoreCase))
            {
                ip = context.Request.Headers["Proxy-Client-IP"];
            }

            if (string.IsNullOrEmpty(ip) || string.Equals("unknown", ip, StringComparison.OrdinalIgnoreCase))
            {
                ip = context.Request.Headers["WL-Proxy-Client-IP"];
            }

            if (string.IsNullOrEmpty(ip) || string.Equals("unknown", ip, StringComparison.OrdinalIgnoreCase))
            {
                ip = context.Connection.RemoteIpAddress.ToString();
            }

            ip = IpUtils.ValidClientIP(ip);
            return(ip);
        }
        public void IpToDecimal(string ip, string expectedDecimalIp, AddressFamily expectedAddressFamily)
        {
            var result = IpUtils.IpToDecimal(ip, out var addressFamily);

            Assert.Equal(result, expectedDecimalIp);
            Assert.Equal(addressFamily, expectedAddressFamily);
        }
Exemple #3
0
        public PooledClient(string endpointList)
        {
            var endpoints = IpUtils.ParseEndpointList(endpointList);

            thriftFactory = new ThriftFactory <TSampleService.Iface>(endpoints, SocketTimeout,
                                                                     socket => new TSampleService.Client(new TBinaryProtocol(socket)));
        }
Exemple #4
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (!IpUtils.ValidateParams(tbServerIp.Text, tbServerName.Text, out var errorMessage))
            {
                MessageBox.Show(this,
                                errorMessage,
                                "Некорректые параметры",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                return;
            }

            var serverIp = tbServerIp.Text != ""
                ? IPAddress.Parse(tbServerIp.Text)
                : IpUtils.GetLocalIp(tbServerName.Text);

            try
            {
                tcpSender = new Sockets.TcpClient();
                tcpSender.Connect(new IPEndPoint(serverIp, ServerListenerPort));
                lbConnectionStatus.Text = $"Подключен к {serverIp}";
                btnConnect.Enabled      = false;
                btnSend.Enabled         = true;
                btnDisconnect.Enabled   = true;
            }
            catch
            {
                MessageBox.Show(this,
                                "Не удалось подключиться к удаленному серверу. Проверьте правильность ip-адреса или имени сервера.",
                                "Ошибка",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
        }
Exemple #5
0
        private void OnIpTextChange()
        {
            string ip = IpBox.Textbox.Text;

            int amountOfPeriods = ip.Count(x => x == '.');

            if (ip.Any(ch => ch != '.' && !char.IsDigit(ch)) || ip.Split('.').Any(x => x.Length > 3) || amountOfPeriods > 3 || ip.Contains("..") || ip.StartsWith('.'))
            {
                RevertTextBox();
                return;
            }

            void RevertTextBox()
            {
                IpBox.Textbox.Text            = IpTextBefore;
                IpBox.Textbox.SelectionStart  = CaretPositionBefore;
                IpBox.Textbox.SelectionLength = 0;
            }

            IpTextBefore = ip;
            GetCaretPos(out Point p);
            // Returns +9 for each number and +4 for a period. We're finding the amount of periods and adding 6 for each of them, so
            // that they act like a number, in order to be able to count caret position properly. Yeah, ugly.
            CaretPositionBefore = (p.X + amountOfPeriods * 6) / 9;

            bool ipCorrect = IpUtils.IsIpCorrect(ip);

            AddButton.Cursor  = ipCorrect ? AddButtonProps.AllowCursor : AddButtonProps.DisallowCursor;
            IpBox.BorderColor = string.IsNullOrEmpty(ip) || ipCorrect ? IpBoxProps.NeutralColor : IpBoxProps.IncorrectColor;
        }
Exemple #6
0
 public static bool CheckWebServiceClient(out string msg, string clientIp)
 {
     msg = string.Empty;
     if ((WebServiceClientIpList.Count > 0) && (!IpUtils.ContainIp(WebServiceClientIpList, clientIp)))
     {
         msg = "客户端(" + clientIp + ")未被授权访问";
         return(false);
     }
     return(true);
 }
Exemple #7
0
        public void RetrieveAvailableUsers()
        {
            // preparing request
            byte[] byteToSend = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(_me));

            while (_continueRequesting)
            {
                bool timedOut = false;

                // sending request
                _udpClient.Send(byteToSend, byteToSend.Length, _broadcastIp);

                // ip end point used to record address and port of sender
                IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

                while (!timedOut)
                {
                    byte[] recBytes = null;

                    try
                    {
                        // blocked until a message is received
                        recBytes = _udpClient.Receive(ref remoteIpEndPoint);
                    }
                    catch (SocketException e)
                    {
                        if (!e.SocketErrorCode.Equals(SocketError.TimedOut))
                        {
                            throw new Exception("Unexpected exception", e);
                        }

                        timedOut = true;

                        // call the functions registered to the delegate, in particular in userSelection
                        // clearing expired users
                        CleanUsersEvent();
                    }

                    if (!IpUtils.IsSelfMessage(remoteIpEndPoint) && !timedOut)
                    {
                        // reading response
                        string readData = Encoding.ASCII.GetString(recBytes);

                        // parsing available user
                        User availableUser = JsonConvert.DeserializeObject <User>(readData);
                        availableUser.IPAddress  = remoteIpEndPoint.Address.ToString();
                        availableUser.LastUpTime = DateTime.Now;

                        // call the functions registered to the delegate, in particular in userSelection
                        // adding new user
                        AddUserEvent(availableUser);
                    }
                }
            }
        }
Exemple #8
0
        private void ServerForm_Load(object sender, EventArgs e)
        {
            tbPcName.Text    = Dns.GetHostName();
            tbIpAddress.Text = IpUtils.GetLocalIp(tbPcName.Text).ToString();

            udpServer = new UdpClient(ServerListenerPort);
            var thread = new Thread(InitListener);

            thread.Start();

            lbStatus.Text = "Сервер запущен";
        }
Exemple #9
0
        private void ClientForm_Load(object sender, EventArgs e)
        {
            tbPcName.Text    = Dns.GetHostName();
            tbIpAddress.Text = IpUtils.GetLocalIp(tbPcName.Text).ToString();
            tbMessage.Focus();

            udpServer = new Sockets.UdpClient(ClientListenerPort);
            var thread = new Thread(InitListener);

            thread.Start();

            lbStatus.Text = "Клиент запущен";
        }
Exemple #10
0
        private void ClientForm_Load(object sender, EventArgs e)
        {
            tbPcName.Text = Dns.GetHostName();
            var localIp = IpUtils.GetLocalIp(tbPcName.Text);

            tbIpAddress.Text = localIp.ToString();
            tbServerIp.Text  = localIp.ToString();


            var thread = new Thread(InitListener);

            thread.Start();

            lbStatus.Text = "Клиент запущен";
        }
Exemple #11
0
        private static IPEndPoint GetLocalEndPointOrDefault()
        {
            IPAddress address;

            try
            {
                // get an ip address and use Loopback if none found
                address = IpUtils.GetLocalIpAddress() ?? IPAddress.Loopback;
            }
            catch (Exception)
            {
                // on failure, use Loopback
                address = IPAddress.Loopback;
            }

            return(new IPEndPoint(address, 0));
        }
Exemple #12
0
        private void btnSend_Click(object sender, EventArgs e)
        {
            var message = tbMessage.Text;

            if (!IpUtils.ValidateParams(tbServerIp.Text, tbServerName.Text, message, out var errorMessage))
            {
                MessageBox.Show(this,
                                errorMessage,
                                "Некорректые параметры",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                return;
            }

            var serverIp = tbServerIp.Text != ""
                ? IPAddress.Parse(tbServerIp.Text)
                : IpUtils.GetLocalIp(tbServerName.Text);

            SendMessage(serverIp, message);
        }
Exemple #13
0
        /// <summary>
        /// Construct the sls client with accessId, accessKey and server address,
        /// all other parameters will be set to default value
        /// </summary>
        /// <param name="endpoint">the sls server address(e.g.,http://cn-hangzhou.sls.aliyuncs.com)</param>
        /// <param name="accessKeyId">aliyun accessId</param>
        /// <param name="accessKey">aliyun accessKey</param>
        public LogClient(String endpoint, String accessKeyId, String accessKey, String securityToken)
        {
            if (!endpoint.StartsWith("http://") && !endpoint.StartsWith("https://"))
            {
                endpoint = "http://" + endpoint;
            }
            setEndpoint(endpoint);
            if (IpUtils.IsIpAddress(this._hostName))
            {
                throw new LogException("LogClientError", "client error happens");
            }

            _localMachinePrivateIp = IpUtils.GetLocalMachinePrivateIp();
            _accessKeyId           = accessKeyId;
            _accessKey             = accessKey;
            _securityToken         = securityToken;
            serviceClient          = ServiceClient.Create(new ClientConfiguration());
            serviceClient.Configuration.ConnectionTimeout = LogConsts.DEFAULT_SLS_CONNECT_TIMEOUT;
            serviceClient.Configuration.ReadWriteTimeout  = LogConsts.DEFAULT_SLS_READWRT_TIMEOUT;
        }
        public async Task <StatisticsClient> StartClientWithRetries()
        {
            _attempt = 0;
            _siloSettings.SiloAddresses ??= new List <string>();
            _siloSettings.SiloAddresses.Add(IpUtils.IpAddress().ToString());

            var innerClient = new ClientBuilder()
                              .UseStaticClustering(_siloSettings.SiloAddresses.Select(a => new IPEndPoint(IPAddress.Parse(a), _siloSettings.SiloPort)).ToArray())
                              .Configure <ClusterOptions>(options =>
            {
                options.ClusterId = _oskSettings.ClusterId;
                options.ServiceId = _oskSettings.ServiceId;
            })
                              .ConfigureLogging(logging => logging.AddConsole())
                              .AddSimpleMessageStreamProvider("OSKProvider")
                              .Build();

            await innerClient.Connect(RetryFilter);

            Console.WriteLine("Client successfully connect to silo host");

            return(new StatisticsClient(innerClient, new NLogLogger(LogManager.GetCurrentClassLogger())));
        }
Exemple #15
0
        public void Listen()
        {
            while (_statusAvailableEvent.WaitOne())
            {
                try
                {
                    // ip end point used to record address and port of sender
                    IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

                    // blocked until a message is received
                    byte[] recBytes = _udpServer.Receive(ref remoteIpEndPoint);

                    if (!IpUtils.IsSelfMessage(remoteIpEndPoint))
                    {
                        // reading requester user
                        //string readData = Encoding.ASCII.GetString(recBytes);

                        //User requesterUser = JsonConvert.DeserializeObject<User>(readData);
                        //requesterUser.IPAddress = remoteIpEndPoint.Address.ToString();

                        // updating machine identity
                        UpdateMe();

                        // preparing response
                        byte[] byteToSend = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(_me));

                        // sending response
                        _udpServer.Send(byteToSend, byteToSend.Length, remoteIpEndPoint);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("problems while udp responding");
                    Console.WriteLine(e);
                }
            }
        }
        public void IpToPaddedDecimal(string ip, string expectedDecimalIp)
        {
            var result = IpUtils.IpToPaddedDecimal(ip);

            Assert.Equal(result, expectedDecimalIp);
        }
Exemple #17
0
        public static Task Main(string[] args)
        {
            var oskSettings  = new OskSettings();
            var siloSettings = new SiloSettings();

            var configuration = new ConfigurationBuilder()
                                .AddJsonFile("appsettings.json", true, true)
                                .Build();

            configuration.GetSection("OskSettings").Bind(oskSettings);
            configuration.GetSection("SiloSettings").Bind(siloSettings);

            if (siloSettings.MaxCpuLoad < 100)
            {
                Task.Run(() => CpuOptimizer.Start(siloSettings.MaxCpuLoad, new CancellationToken()));
            }

            return(new HostBuilder()
                   .UseOrleans(builder =>
            {
                builder.UseLocalhostClustering()
                .ConfigureServices(services =>
                {
                    services.AddMongoUtils();
                    services.AddSingleton(oskSettings);
                    services.AddSingleton(siloSettings);
                    services.AddScoped <IAsyncLogger, NLogLogger>();
                    services.AddSingleton <IAssemblyCache, MemoryAssemblyCache>();
                    services.AddSingleton <IAssemblyMembersCache, MemoryAssemblyMembersCache>();
                })
                .Configure((Action <SchedulingOptions>)(options => options.AllowCallChainReentrancy = false))
                .Configure((Action <ClusterOptions>)(options =>
                {
                    options.ClusterId = oskSettings.ClusterId;
                    options.ServiceId = oskSettings.ServiceId;
                }))
                .Configure((Action <EndpointOptions>)(options => options.AdvertisedIPAddress = IpUtils.IpAddress()))
                .ConfigureApplicationParts(parts => AddParts(parts, siloSettings).WithReferences())
                .UseDashboard(options => {
                    options.Host = "*";
                    options.Port = 8080;
                    options.HostSelf = true;
                    options.CounterUpdateIntervalMs = 1000;
                })
                .AddMemoryGrainStorage(name: "StatisticsGrainStorage")
                .AddSimpleMessageStreamProvider("OSKProvider", c => c.OptimizeForImmutableData = true);
            })
                   .ConfigureLogging(builder => builder.AddConsole())
                   .RunConsoleAsync());
        }
Exemple #18
0
        public void IsIpAddressInvalidIpV4Test()
        {
            const string validIPv4 = "172.16.2541";

            Assert.IsFalse(IpUtils.IsIpAddress(validIPv4));
        }
Exemple #19
0
        public void IsIpAddressInvalidIpV6Test()
        {
            const string validIPv6 = "2001:db8:1234:0000";

            Assert.IsFalse(IpUtils.IsIpAddress(validIPv6));
        }
Exemple #20
0
 public string ResolveListenIp()
 {
     return(_resolvedListenIp ??= IpUtils.ResolveIp(ListenIp));
 }
Exemple #21
0
        public void IsValidPublicIpTest()
        {
            const string ip = "64.71.222.37";

            Assert.IsTrue(IpUtils.IsValidPublicIp(ip));
        }
Exemple #22
0
        public void IsNotValidPublicIpTest()
        {
            const string ip = "10.0.0.0";

            Assert.IsFalse(IpUtils.IsValidPublicIp(ip));
        }
Exemple #23
0
        public void IsValidLoopbackIpTest()
        {
            const string ip = "127.0.0.1";

            Assert.IsTrue(IpUtils.IsLoopBack(ip));
        }
Exemple #24
0
        public void IsIpAddressValidIpV4Test()
        {
            const string validIPv4 = "172.16.254.1";

            Assert.IsTrue(IpUtils.IsIpAddress(validIPv4));
        }
Exemple #25
0
        public void SetAuthentication(WebSocketServer webSocketServer)
        {
            var password          = HasToken() ? LoadToken() : CreateToken();
            var connectionPayload = new ConnectionPayload(webSocketServer.IsSecure ? "wss" : "ws", IpUtils.GetLocalIpAddress(), webSocketServer.Port, "user", password);

            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            var             qrCodeData  = qrGenerator.CreateQrCode(JsonConvert.SerializeObject(connectionPayload), QRCodeGenerator.ECCLevel.Q);

            connectionQRCode = new PngByteQRCode(qrCodeData);

            webSocketServer.AuthenticationSchemes = WebSocketSharp.Net.AuthenticationSchemes.Basic;
            webSocketServer.UserCredentialsFinder = (id) =>
            {
#if LOCAL
                return(new WebSocketSharp.Net.NetworkCredential("username", "password"));
#else
                return(id.Name == connectionPayload.AuthenticationUsername ?
                       new WebSocketSharp.Net.NetworkCredential(connectionPayload.AuthenticationUsername, connectionPayload.AuthenticationPassword) :
                       null);
#endif
            };
        }
Exemple #26
0
 /// <summary>
 /// Creates an FtpFileReceiverClient.
 /// </summary>
 /// <param name="path">Path to save files. Eg.: "D:/"</param>
 public FtpFileReceiverClient(string path)
 {
     ipUtils   = new IpUtils();
     this.path = path;
 }
Exemple #27
0
 public string ResolvePublicIp()
 {
     return(_resolvedPublicIp ??= IpUtils.ResolveIp(PublicIp));
 }