Esempio n. 1
0
        public void StringToUIntTest()
        {
            var u = IPAddressHelper.IPv4AddressToUInt("123.232.112.12");
            var s = IPAddressHelper.ToIPv4Address(u);

            Assert.AreEqual("123.232.112.12", s);
        }
Esempio n. 2
0
        public void ByteArrayToStringTest()
        {
            var b = new byte[] { 123, 232, 112, 12 };
            var s = IPAddressHelper.ToIPv4Address(b, 0);

            Assert.AreEqual("123.232.112.12", s);
        }
Esempio n. 3
0
        /// <summary>
        /// Creates a background thread to find and update the external IP address text.
        /// </summary>
        void UpdateExternalIP()
        {
            var externalIP = string.Empty;
            var hostName   = string.Empty;

            var w = new BackgroundWorker();

            // Create the work method
            w.DoWork += delegate
            {
                hostName   = Dns.GetHostName();
                externalIP = IPAddressHelper.GetExternalIP();
                if (string.IsNullOrEmpty(externalIP))
                {
                    externalIP = "[Failed to get external IP]";
                }
            };

            // Create the updater
            w.RunWorkerCompleted += delegate
            {
                lblIP.Invoke((Action) delegate { lblIP.Text = string.Format("{0} ({1})", externalIP, hostName); });
                w.Dispose();
            };

            // Run the worker
            w.RunWorkerAsync();
        }
Esempio n. 4
0
        public void Start()
        {
            if (!_started)
            {
                _localIP = IPAddressHelper.GetLocalIp();
                Gateway gw = InfoService.Instance.CurrentGateway; //当前网关配置。
                _localAOR = $"{gw.SipNumber}@{_localIP}";

                //m_stack = new SIP_Stack();
                //m_stack.Realm = "seecool"; //本地域,当需要验证远程注册用户的时候,发送此域。
                //m_stack.UserAgent = "NetGateway www.seecool.cc";//必须设置。
                //m_stack.Error += M_stack_Error;
                //m_stack.RequestReceived += M_stack_RequestReceived;
                //m_stack.ResponseReceived += M_stack_ResponseReceived;
                //m_stack.Logger.WriteLog += Logger_WriteLog;

                //用户注册授权凭证,向远程服务器注册本机时需要。
                //m_stack.Credentials.Add(new NetworkCredential("admin", "admin", "seecool"));

                //添加本地端口绑定
                IPBindInfo[] bindInfo = new IPBindInfo[] {
                    new IPBindInfo(_localIP, BindInfoProtocol.UDP, IPAddress.Parse(_localIP), gw.Port),
                    new IPBindInfo(_localIP, BindInfoProtocol.TCP, IPAddress.Parse(_localIP), gw.Port)
                };

                Stack.BindInfo = bindInfo;
                Stack.Start();
                addVirtualServer();
                _deviceMgr.Start();
                _started = true;
            }
        }
Esempio n. 5
0
        protected override async Task <HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {
            string accountName = AccountSession.AccountName;
            long   accountId   = AccountSession.AccountID;
            string response    = string.Empty;

            string requestBody = await request.Content.ReadAsStringAsync();

            var result = await base.SendAsync(request, cancellationToken);

            if (result.Content != null)
            {
                response = await result.Content.ReadAsStringAsync();
            }

            NLogManager.LogMessage($"REQUEST BODY => API [{request.RequestUri}]" + "\n" +
                                   $"METHOD [{request.Method}] " + "\n" +
                                   $"BODY [{requestBody}] " + "\n" +
                                   $"RESPONSE [{response}] " + "\n" +
                                   $"IP [{IPAddressHelper.GetClientIP()}] " + "\n" +
                                   $"AccountName [{accountName}] " + "\n" +
                                   $"AccountID [{accountId}]");

            return(result);
        }
Esempio n. 6
0
        public void recordLogininfor(string userName, char status, string message, RequestBasicInfo info)
        {
            SysLoginInfor model = new SysLoginInfor();

            model.UserName = userName;
            model.status   = status;
            model.msg      = message;
            var task = IPAddressHelper.getRealAddressByIP(info.Ip);

            model.ipaddr        = info.Ip;
            model.LoginLocation = task.Result;
            model.Browser       = info.Device;
            model.Os            = info.Os;
            model.LoginTime     = DateTime.Now;

            //这里为社么不用这个方法 原因:
            //因为这个方法是在一个Task 任务里启动的,这样子会造成 注入的仓储相关的dbcontent 其实已经被dispose了。
            //如果不用多线程,this.Add方法是完全可以用的;
            //this.Add(model);
            using (var context = new YouGeDbContext(option))
            {
                context.Set <SysLoginInfor>().Add(model);
                context.SaveChanges();
            }
        }
Esempio n. 7
0
        public virtual async Task <IActionResult> ChoosePlan()
        {
            try
            {
                Logger.LogInformation("Getting user.");
                var user = await UserDbServiceHelper.GetAppUserByIdAsync(UserDbService, UserInContextHelper.GetCurrentUserId(HttpContext));

                var planStartId = user.GetPlanId();
                ViewBag.PrePlan = planStartId > 0 ? true : false;
                Logger.LogInformation($"Got user. User ID '{user.Id}', existing plan/plan start ID '{planStartId}'.");
                //Dev plans are only included if ip is privileged and user is admin
                var ipIsPriviledged = IPAddressHelper.IsCurrentUserIpPrivileged(HttpContext, Settings);
                var isAdmin         = user.IsAdmin;;
                Logger.LogInformation($"User IP is priviledged : '{ipIsPriviledged}'.");
                Logger.LogInformation($"User is admin : '{isAdmin}'.");
                bool includeDev = ipIsPriviledged && isAdmin;
                Logger.LogInformation($"Dev plans are being included : '{includeDev}'");
                Logger.LogInformation("Listing plans now.");
                var plans = PlanReader.GetAvailableUpgrades(planStartId, includeDev);
                Logger.LogInformation($"Total '{plans.Count}' have been listed.");
                Logger.LogInformation($"Choose plan view name is {Views.Shopify.ChoosePlan}.");
                return(View(Views.Shopify.ChoosePlan, plans));
            }
            catch (Exception ex)
            {
                Logger.LogWarning("Error occurred while executing ChoosePlan())");
                LogGenericError(ex);
                throw ex;
            }
        }
Esempio n. 8
0
        private string MaskComputer(IPAddressHelper ipAddressHelper, string maskedNetwork, List <string> usedMaskedComputer)
        {
            var maskedComputer = GenerateUniqueIP(usedMaskedComputer, ipAddressHelper.GenerateIPComputerAddress);
            var maskedIP       = BuildIP(maskedNetwork, maskedComputer);

            return(maskedIP);
        }
Esempio n. 9
0
        /// <summary>
        /// Xóa ip action cache
        /// </summary>
        /// <param name="action">truyền vào tên action</param>
        /// <returns></returns>
        public static void IpActionDelete(string action)
        {
            string ip = IPAddressHelper.GetClientIP();

            System.Runtime.Caching.ObjectCache cache = System.Runtime.Caching.MemoryCache.Default;
            cache.Remove("P" + ip.ToLower() + "_" + action);
        }
Esempio n. 10
0
        //---------------------------------------------------------------------------------------------------------------------------------------------------------
        /// <summary>
        ///     Using the OnUnload method for performance benchmarking of pages
        /// </summary>
        protected override void OnUnload(EventArgs e)
        {
            // Performance benchmarking ...
            DateTime dt2 = DateTime.Now;
            TimeSpan t1  = dt2.Subtract(dt1);

            string currentPageName = HttpContext.Current.Request.Url.AbsoluteUri;

            int currentUserID = (Authorisation.CurrentUser != null) ? Authorisation.CurrentUser.ID : 0;

            // 14-Jan-2015 - Get the IP Address
            string srcIPAddress = IPAddressHelper.GetIP4OrAnyAddressFromHTTPRequest();

            // 11-Mar-2016 - Sanity check - when pages crash, dt1 is not always set so is the null date, so if the difference between dt1 and dt2 is more than one day (!!), use dt2
            // 16-Mar-2016 - And reset the timespan so it is sensible, otherwise the average response time queries in view page performance do not work!
            // you can find the crashed pages in the db with this query: SELECT * FROM Log_PageRequests WHERE Server_Render_Speed > 63593600000000;
            DateTime logTime = dt1;

            if (t1.TotalMilliseconds > 86400000)
            {
                logTime = dt2;
                t1      = new TimeSpan(0, 0, 0, 0, 50);
            }

            LoggerDB.LogPageRequestInDatabase(MGLSessionInterface.Instance().Config, MGLApplicationInterface.Instance().ApplicationName,
                                              Session.SessionID, MGLSessionInterface.Instance().SessionID, currentPageName, dt2, t1.TotalMilliseconds, currentUserID, srcIPAddress);
//            Logger.LogError(currentPageName + "Time to build page: " + t1.TotalMilliseconds);

            base.OnUnload(e);
        }
Esempio n. 11
0
        public void IsLocalOrLandAddress_Returns_Correct_Value(string ipAddress, bool expected)
        {
            var address = IPAddress.Parse(ipAddress);

            var actual = IPAddressHelper.IsLocalOrLanAddress(address);

            Assert.AreEqual(expected, actual);
        }
Esempio n. 12
0
        public void ParseIPv4String_001()
        {
            var _IPv4Address = IPAddressHelper.Parse("141.24.12.2");

            Assert.IsTrue(_IPv4Address is IIPAddress);
            Assert.IsTrue(_IPv4Address is IPv4Address);
            Assert.IsFalse(_IPv4Address is IPv6Address);
        }
Esempio n. 13
0
        public void UIntToStringTest()
        {
            var b = new byte[] { 123, 232, 112, 12 };
            var u = IPAddressHelper.IPv4AddressToUInt(b, 0);
            var s = IPAddressHelper.ToIPv4Address(u);

            Assert.AreEqual("123.232.112.12", s);
        }
Esempio n. 14
0
        public void ParseIPv6ByteArray()
        {
            var _IPv4Address = IPAddressHelper.Build(new Byte[] { 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0 });

            Assert.IsTrue(_IPv4Address is IIPAddress);
            Assert.IsFalse(_IPv4Address is IPv4Address);
            Assert.IsTrue(_IPv4Address is IPv6Address);
        }
Esempio n. 15
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            var userLoginTrace = new UserLogTrace
            {
                DatePosted        = DateTime.Now,
                IpAddress         = IPAddressHelper.GetIpAddress(),
                IsLoggedSucceeded = false,
                PhoneNumber       = model.UserName ?? "00000000000"
            };

            if (!this.ModelState.IsValid)
            {
                var errors = ModelState.Values.SelectMany(state => state.Errors).ToList();
                foreach (var error in errors)
                {
                    this.ModelState.AddModelError(string.Empty, error.ErrorMessage);
                }

                this.Data.UserLogTrace.Add(userLoginTrace);
                this.Data.SaveChanges();

                return(this.View(model));
            }

            // transform string value to bool value
            var isRememberMe = string.Compare(model.RememberMe, "on", StringComparison.OrdinalIgnoreCase) == 0;

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result =
                await this.SignInManager.PasswordSignInAsync(model.UserName, model.Password, isRememberMe, false);

            if (result == SignInStatus.Success)
            {
                userLoginTrace.IsLoggedSucceeded = true;
            }

            this.Data.UserLogTrace.Add(userLoginTrace);
            this.Data.SaveChanges();

            switch (result)
            {
            case SignInStatus.Success:
                return(this.RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(this.View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(this.RedirectToAction("SendCode", new { ReturnUrl = returnUrl, model.RememberMe }));

            case SignInStatus.Failure:
            default:
                this.ModelState.AddModelError(string.Empty, Resources.Resources.InvalidLoginAttempt);
                return(this.View(model));
            }
        }
Esempio n. 16
0
        public void GetNetworkAddress(string input, string mask, string expected)
        {
            IPAddress address     = IPAddress.Parse(input);
            IPAddress maskAddress = IPAddress.Parse(mask);

            Assert.Equal(
                expected,
                IPAddressHelper.GetNetworkAddress(address, maskAddress).ToString());
        }
Esempio n. 17
0
        public void TestGenerateIPComputerAddress()
        {
            var ipAddressHelper     = new IPAddressHelper();
            var ipIPComputerAddress = ipAddressHelper.GenerateIPComputerAddress();
            var ipRegex             = new Regex(@"\b\d{1,3}");
            var isMatch             = ipRegex.IsMatch(ipIPComputerAddress);

            Assert.IsTrue(isMatch);
        }
Esempio n. 18
0
        public void TestGenerateIPNetworkAddress()
        {
            var ipAddressHelper  = new IPAddressHelper();
            var ipNetworkAddress = ipAddressHelper.GenerateIPNetworkAddress();
            var ipRegex          = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\b");
            var isMatch          = ipRegex.IsMatch(ipNetworkAddress);

            Assert.IsTrue(isMatch);
        }
Esempio n. 19
0
        public void ToFromUIntTest()
        {
            var u  = IPAddressHelper.IPv4AddressToUInt("123.232.112.12");
            var s  = IPAddressHelper.ToIPv4Address(u);
            var u2 = IPAddressHelper.IPv4AddressToUInt(s);

            Assert.AreEqual("123.232.112.12", s);
            Assert.AreEqual(u, u2);
        }
Esempio n. 20
0
        public IGeolocationResult GetLocation(RequestContext requestContext)
        {
            if (requestContext == null)
            {
                throw new ArgumentNullException(nameof(requestContext));
            }

            return(GetLocation(IPAddressHelper.GetRequestIpAddress(requestContext.HttpContext.Request)));
        }
Esempio n. 21
0
        /// <summary>
        /// Đếm số lượt của hành động dựa trên IP
        /// </summary>
        /// <param name="action">truyền vào tên action</param>
        /// <returns></returns>
        public static int IpActionCounter(string action)
        {
            string ip = IPAddressHelper.GetClientIP();

            System.Runtime.Caching.ObjectCache cache = System.Runtime.Caching.MemoryCache.Default;
            object cacheCounter = cache.Get("P" + ip.ToLower() + "_" + action);

            return(Convert.ToInt32(cacheCounter));
        }
Esempio n. 22
0
            public void TestIt()
            {
                var addressBytes = IPAddressHelper.GetAddressBytes(0x11223344);

                addressBytes.Length.ShouldEqual(4);
                addressBytes[0].ShouldEqual(0x11);
                addressBytes[1].ShouldEqual(0x22);
                addressBytes[2].ShouldEqual(0x33);
                addressBytes[3].ShouldEqual(0x44);
            }
Esempio n. 23
0
        public void ToFromBytesTest()
        {
            var b  = new byte[] { 123, 232, 112, 12 };
            var u  = IPAddressHelper.IPv4AddressToUInt(b, 0);
            var s  = IPAddressHelper.ToIPv4Address(u);
            var u2 = IPAddressHelper.IPv4AddressToUInt(s);

            Assert.AreEqual("123.232.112.12", s);
            Assert.AreEqual(u, u2);
        }
Esempio n. 24
0
        internal VirtualDevice(CCTVStaticInfo real, Gateway gw, string sipNum, SIP_Registrar _reg)
        {
            _realInfo  = real;
            _sipNum    = sipNum;
            _gateway   = gw;
            _registrar = _reg;
            string localIP = IPAddressHelper.GetLocalIp();

            _localAOR = $"{sipNum}@{localIP}";
        }
Esempio n. 25
0
        public void TestFindIPAddressSingle()
        {
            var text            = "03/22 08:51:06 INFO   :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0";
            var ipAddressHelper = new IPAddressHelper();
            var ips             = text.FindIPAddress().ToArray();

            Assert.IsNotNull(ips);
            Assert.AreEqual(ips.Length, 1);
            Assert.AreEqual(ips[0], "129.1.1.1");
        }
Esempio n. 26
0
            public void TestIt()
            {
                Catch(() => { IPAddressHelper.GetAddressValue(null); }).ShouldBeOfType <ArgumentNullException>();
                Catch(() => { IPAddressHelper.GetAddressValue(new byte[0]); }).ShouldBeOfType <ArgumentException>();
                Catch(() => { IPAddressHelper.GetAddressValue(new byte[] { 0, 1 }); }).ShouldBeOfType <ArgumentException>();

                var addressValue = IPAddressHelper.GetAddressValue(new byte[] { 0x11, 0x22, 0x33, 0x44 });

                addressValue.ShouldEqual(0x11223344);
            }
Esempio n. 27
0
        //--//

        public CoreTest(ILogger logger)
        {
            if (logger == null)
            {
                throw new ArgumentException("Cannot run tests without logging");
            }

            _completed = new AutoResetEvent(false);

            _logger = logger;

            _rand = new Random( );
            _totalMessagesSent   = 0;
            _totalMessagesToSend = 0;
            _gatewayQueue        = new GatewayQueue <QueuedItem>( );

#if MOCK_SENDER
            _sender = new MockSender <SensorDataContract>(this);
#else
            IotHubConfig iotHubConfig = Loader.GetIotHubConfig( );

            _sender = new MessageSender <SensorDataContract>(iotHubConfig.IotHubConnectionString, _logger);
#endif

            _batchSenderThread = new BatchSenderThread <QueuedItem, SensorDataContract>(
                _gatewayQueue,
                _sender,
                dataTransform: null,
                serializedData: m => (m == null) ? null : m.JsonData,
                logger: _logger
                );

            string gatewayIPAddressString = string.Empty;
            IPAddressHelper.GetIPAddressString(ref gatewayIPAddressString);

            DataTransformsConfig dataTransformsConfig = Loader.GetDataTransformsConfig( );
            if (dataTransformsConfig.AttachIP || dataTransformsConfig.AttachTime)
            {
                Func <string, SensorDataContract> transform = (m => DataTransforms.SensorDataContractFromString(m, _logger));

                if (dataTransformsConfig.AttachTime)
                {
                    var transformPrev = transform;
                    transform = (m => DataTransforms.AddTimeCreated(transformPrev(m)));
                }

                if (dataTransformsConfig.AttachTime)
                {
                    var transformPrev = transform;
                    transform = (m => DataTransforms.AddIPToLocation(transformPrev(m), gatewayIPAddressString));
                }

                _gatewayTransform = (m => DataTransforms.QueuedItemFromSensorDataContract(transform(m)));
            }
        }
Esempio n. 28
0
 public ActionResult SubmitMessageBoardInfo(FormCollection form)
 {
     if (!ModelState.IsValid)
     {
         return(Json(new { Success = true, ErrorMessage = "提交内容有误,留言失败,请稍后重试!" }, JsonRequestBehavior.DenyGet));
     }
     try
     {
         var host           = HttpContext.Request.Url.Host.ToString() ?? string.Empty;
         var requestUrl     = HttpContext.Request.Url.ToString() ?? string.Empty;
         var urlReferrer    = HttpContext.Request.UrlReferrer.ToString();
         var userName       = HttpUtility.UrlDecode(form["nickname"].ToString() ?? string.Empty);
         var phone          = HttpUtility.UrlDecode(form["cellphone"].ToString() ?? string.Empty);
         var sourceurl      = HttpUtility.UrlDecode(form["sourceurl"].ToString() ?? string.Empty);//
         var isVerCode      = HttpUtility.UrlDecode(form["isVerCode"].ToString() ?? string.Empty);
         var messageContent = HttpUtility.UrlDecode(form["messageInfo"].ToString() ?? string.Empty);
         if (isVerCode == "1")
         {
             var verCode       = HttpUtility.UrlDecode(form["vercode"].ToString() ?? string.Empty);
             var IsCheckedPass = null != Session["VerCode"] && Session["VerCode"].ToString() == verCode;
             if (!IsCheckedPass)
             {
                 return(Json(new { Success = false, ErrorMessage = "验证码有误,请重新填写!" }, JsonRequestBehavior.DenyGet));
             }
         }
         if (string.IsNullOrEmpty(userName))
         {
             return(Json(new { Success = false, ErrorMessage = "姓名不能为空!" }, JsonRequestBehavior.DenyGet));
         }
         if (string.IsNullOrEmpty(phone) || !IsCheckPhone(phone))
         {
             return(Json(new { Success = false, ErrorMessage = "手机号码有误,请重新填写!" }, JsonRequestBehavior.DenyGet));
         }
         var entity = new MessageBoard
         {
             UserName       = HttpUtility.UrlDecode(userName.Trim()),
             Phone          = HttpUtility.UrlDecode(phone.Trim()),
             MessageContent = HttpUtility.UrlDecode(messageContent.Trim()),
             ClientIp       = IPAddressHelper.GetClientIp(),
             LocalIp        = IPAddressHelper.GetLocalIp(),
             RequestUrl     = string.IsNullOrEmpty(sourceurl)? requestUrl: sourceurl,
             UrlReferrer    = urlReferrer,
             Host           = host,
             CreateTime     = DateTime.Now
         };
         var messageBoard = new MessageBoardBLL();
         messageBoard.Add(entity);
         return(Json(new { Success = true, }, JsonRequestBehavior.DenyGet));
     }
     catch (Exception ex)
     {
         Log.Error("留言板留言出现未处理异常", ex.ToString());
         return(Json(new { Success = false, ErrorMessage = "留言失败,请稍后重试!" }, JsonRequestBehavior.DenyGet));
     }
 }
Esempio n. 29
0
        internal RTPServer(int localPort, string videoId)
        {
            _rtpHelper     = new RTPPackHelper();
            _hTrigger      = new RTPHeaderTrigger();
            _ups           = new UnpackPS();
            _ups.Unpacked += _ups_Unpacked;

            _localIP   = IPAddressHelper.GetLocalIp();
            _localPort = localPort;
            _videoId   = videoId;
            _targets   = new Dictionary <string, TargetItem>();
        }
Esempio n. 30
0
        private IEnumerable <string> MaskLines()
        {
            var maskedLines       = _lines.ToArray();
            var ipAddressHelper   = new IPAddressHelper();
            var usedMaskedNetwork = new List <string>();

            foreach (var network in _mappedIP.Keys)
            {
                maskedLines = MaskNetworkComputers(network, maskedLines, ipAddressHelper, usedMaskedNetwork);
            }
            return(maskedLines);
        }