Beispiel #1
0
        public void get_ip_from_UserHostAddress()
        {
            var httpRequest = MockHttpRequestBase("44.34.56.78");
            var ipHelper    = new IPHelper();

            Assert.Equal("44.34.56.78", ipHelper.GetClientIP(httpRequest).ToString());
        }
Beispiel #2
0
        public void InsertTest()
        {
            LineDataProvider  _provider = new LineDataProvider();
            double            count     = 0;
            List <string>     ipList    = new IPHelper().GetIPListFromStartHost("192.167.1.1", 20, out count);
            List <OrganModel> organList = new List <OrganModel>();
            List <LineModel>  lineList  = new List <LineModel>();
            double            x         = 0;
            double            y         = 0;
            int    j = 0;
            Random r = new Random();

            for (int i = 0; i < 1000; i++)
            {
                x = r.Next(-200, 200) * 0.1;
                y = r.Next(-200, 200) * 0.1;
                organList.Add(new OrganModel()
                {
                    Name = "数据中心" + i, Description = i.ToString(), ParentId = 43, X = x.ToString(), Y = y.ToString()
                });
            }
            new OrganDataProvider().Insert(organList);

            List <OrganModel> newOrganList = new OrganDataProvider().GetAllItems("", "", "");

            foreach (var item in ipList)
            {
                j = r.Next(43, 1000);
                lineList.Add(new LineModel()
                {
                    AlarmMax = 3, Description = item, LineIP = item, OrganizationId = newOrganList[j].Id, LineType = LineType.mainline, PingInterval = 30, Pingsize = 32, Pingtimes = 4, ServiceProvider = ServiceProviderType.ChinaMobile, Timeout = 2, Name = item
                });
            }
            _provider.Insert(lineList);
        }
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (context == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            //访问记录
            // var visit = RequestHelper.Visit();
            //VisitQueueInstance.Add(visit);

            var inWriteList = IPHelper.InWriteList(RequestHelper.GetClientIp());

            if (!inWriteList)
            {
                context.Result = new RedirectResult("/404.html");
            }
            //允许AllowAnonymous匿名访问
            var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;

            if (controllerActionDescriptor != null)
            {
                var isDefined = controllerActionDescriptor.ControllerTypeInfo.GetCustomAttributes(inherit: true)
                                .Any(a => a.GetType().Equals(typeof(AllowAnonymousAttribute)));

                if (isDefined)
                {
                }
            }


            await base.OnActionExecutionAsync(context, next);
        }
Beispiel #4
0
        public HttpResponseMessage UpdateEssay(Essays obj)
        {
            ReturnHelper rh = new ReturnHelper(200, null, 0, "");

            try
            {
                obj.Update_Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                obj.Ip          = IPHelper.GetHostIP();
                obj.Address     = IPHelper.GetHostAddress(obj.Ip);
                int i = obj.Update(" Essayid=@Essayid", obj.Essayid);
                if (i > 0)
                {
                    rh.msg    = "更新文章成功";
                    rh.totals = i;
                }
                else
                {
                    rh.msg  = "更新文章失败";
                    rh.code = 400;
                }
            }
            catch (Exception e)
            {
                rh.code = 500;
                rh.msg  = "服务器错误,请通知管理员";
            }

            return(ReturnJson(JsonConvert.SerializeObject(rh)));
        }
Beispiel #5
0
        public static void Refresh(IDomainRecord domainRecord, DDNSConfig dnsConfig)
        {
            var current_ip = IPHelper.CurrentIp();
            var records    = domainRecord.GetRecords(dnsConfig.domain);

            if (!string.IsNullOrEmpty(dnsConfig.ignoreRR.Trim()))
            {
                var igs = dnsConfig.ignoreRR.Trim().Split("|");
                records = records.Where(x => x.Type == "A" && !igs.Contains(x.RR));
            }

            if (!records.Any(x => x.Value != current_ip))
            {
                Console.WriteLine($"{DateTime.Now} ip没有改变 {current_ip}");
                return;
            }

            Console.WriteLine($"{DateTime.Now} 更新A解析记录 {current_ip}");

            // 更新记录
            foreach (var item in records)
            {
                //item.Value = current_ip;
                //domainRecord.UpdateRecord(item);
            }
        }
Beispiel #6
0
        public LoginOutput Login(LoginInput input)
        {
            var user = db.Users.FirstOrDefault(u => u.LoginName == input.loginname && u.PassWord == input.password);

            if (user == null)
            {
                return(null);
            }
            else
            {
                if (user.Status == 0)
                {
                    throw new UserFriendlyException("账号未启用");
                }
                else
                {
                    //记录日志
                    //记录IP,登录时间
                    user.LastLoginIP     = IPHelper.GetHostAddress();
                    user.LastLoginTime   = DateTime.Now;
                    db.Entry(user).State = EntityState.Modified;
                    db.SaveChanges();
                }
                return(user.MapTo <LoginOutput>());
            }
        }
Beispiel #7
0
        public HttpResponseMessage AddShort(Shorts obj)
        {
            ReturnHelper rh = new ReturnHelper(200, null, 0, "");

            try
            {
                obj.Shortid     = Guid.NewGuid().ToString("N");
                obj.Report_Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                obj.Ip          = IPHelper.GetHostIP();
                obj.Address     = IPHelper.GetHostAddress(obj.Ip);
                int i = obj.Insert();
                if (i > 0)
                {
                    rh.msg    = "添加记录成功";
                    rh.totals = i;
                }
                else
                {
                    rh.msg  = "添加记录失败";
                    rh.code = 400;
                }
            }
            catch (Exception e)
            {
                rh.code = 500;
                rh.msg  = "服务器错误,请通知管理员";
            }

            return(ReturnJson(JsonConvert.SerializeObject(rh)));
        }
Beispiel #8
0
        public IActionResult Save(cms_ip_manager dto)
        {
            if (!IPHelper.ISIP(dto.start_ip))
            {
                return(Error("起始IP地址错误"));
            }
            if (!IPHelper.ISIP(dto.end_ip))
            {
                return(Error("结束IP地址错误"));
            }
            dto.start_ip_val = IPHelper.IPValue(dto.start_ip);
            dto.end_ip_val   = IPHelper.IPValue(dto.end_ip);
            long id = _ipManagerApp.SaveData(dto);

            if (id > 0)
            {
                dto.id = (int)id;
                if (dto.enable)
                {
                    IPHelper.AddIpRange(dto);
                }
            }
            else
            {
                if (dto.enable)
                {
                    IPHelper.AddIpRange(dto);
                }
                else
                {
                    IPHelper.RemoveIpRange(dto.id);
                }
            }
            return(Success("保存成功"));
        }
Beispiel #9
0
    public static string NetAddConnection(string server, string username, string password)
    {
        Win32Utils.NETRESOURCE netResource = new Win32Utils.NETRESOURCE();
        netResource.dwDisplayType = 1;
        netResource.dwScope       = 0;
        netResource.dwType        = 0;
        netResource.dwUsage       = 2;
        netResource.LocalName     = "";
        netResource.RemoteName    = IPHelper.GetWNetServerString(server);
        netResource.Provider      = (string)null;
        string username1;
        string domain;

        CUtils.SplitUsernameAndDomain(username, out username1, out domain);
        username = !string.IsNullOrEmpty(domain) ? username1 + "@" + domain : server.Replace(':', '-') + "\\" + username1;
        int    num = Win32Utils.WNetAddConnection2(ref netResource, password, username, 0);
        string str;

        switch (num)
        {
        case 0:
        case 1219:
        case 71:
            str = (string)null;
            break;

        default:
            str = Win32Utils.FormatWin32ErrorMessage((uint)num);
            break;
        }
        return(str);
    }
Beispiel #10
0
        public ActionResult Index()
        {
            var mvcName = typeof(Controller).Assembly.GetName();
            var isMono  = Type.GetType("Mono.Runtime") != null;

            ViewData["Version"] = mvcName.Version.Major + "." + mvcName.Version.Minor;
            ViewData["Runtime"] = isMono ? "Mono" : ".NET";
            var ipCity = IPHelper.GetIPCitys()?.ToLower();

            if (string.IsNullOrEmpty(ipCity) || ipCity == "未知" || ipCity == "内网ip")
            {
                ipCity = "苏州";
            }
            var request = new StoreSearchRequest
            {
                City     = ipCity,
                PageSize = 4,
            };
            var list = new List <StoreSearchModel>();
            var data = StoresAccess.GetStoreList(request);

            if (data != null && data.Any())
            {
                data = data.Take(request.PageSize).ToList();
                list = StoresAccess.ConvertList(data);
            }
            ViewBag.List     = list;
            ViewBag.AreaList = HotCityList.List;
            return(View());
        }
Beispiel #11
0
        public WKSType Modify(TimeSpan?ttl, string internetAddress, string ipProtocol
                              , string services)
        {
            //Why the hell microsoft made that method so complicated?! :-)
            ManagementBaseObject inParams = m_mo.GetMethodParameters("Modify");

            if ((ttl != null) && (ttl != this.TTL))
            {
                inParams["TTL"] = ttl.Value.TotalSeconds;
            }
            if ((internetAddress != null) && (internetAddress != this.InternetAddress))
            {
                inParams["InternetAddress"] = IPHelper.ToUint32(internetAddress);
            }
            if ((ipProtocol != null) && (ipProtocol != this.IPProtocol))
            {
                inParams["IPProtocol"] = IPHelper.GetProtoByName(ipProtocol);
            }
            if ((services != null) && (services != this.Services))
            {
                inParams["Services"] = IPHelper.GetServByName(services, ipProtocol);
            }

            try
            {
                return(new WKSType(new ManagementObject(m_mo.Scope, new ManagementPath(m_mo.InvokeMethod("Modify", inParams, null)["RR"].ToString()), null)));
            }
            catch (ManagementException me)
            {
                throw new WMIException(me);
            }
        }
Beispiel #12
0
        /// <summary>
        /// This method updates the TTL, Responsible Mailbox, and Error Mailbox to the values specified as the input parameters of this method. If a new value for a parameter is not specified, then the current value for the parameter is not changed. The method returns a reference to the modified object as an output parameter.
        /// </summary>
        /// <param name="ttl">Optional - Time, in seconds, that the RR can be cached by a DNS resolver.</param>
        /// <param name="errorMailbox">Optional - FQDN specifying a mailbox to receive error messages related to either the mailing list, or to the mailbox specified by the owner name of the MINFO record.</param>
        /// <param name="responsibleMailbox">Optional - FQDN specifying a mailbox responsible for the mailing list or mailbox specified in the record's Owner Name.</param>
        /// <returns>the modified object.</returns>
        public MINFOType Modify(TimeSpan?ttl, string responsibleMailbox, string errorMailbox)
        {
            ManagementBaseObject inParams = m_mo.GetMethodParameters("Modify");

            if ((ttl != null) && (ttl != this.TTL))
            {
                inParams["TTL"] = ttl.Value.TotalSeconds;
            }
            if ((!string.IsNullOrEmpty(responsibleMailbox)) && (responsibleMailbox != this.ResponsibleMailbox))
            {
                inParams["ResponsibleMailbox"] = IPHelper.FixHostnames(responsibleMailbox);
            }
            if ((!string.IsNullOrEmpty(errorMailbox)) && (errorMailbox != this.ErrorMailbox))
            {
                inParams["ErrorMailbox"] = IPHelper.FixHostnames(errorMailbox);
            }

            try
            {
                return(new MINFOType(new ManagementObject(m_mo.Scope, new ManagementPath(m_mo.InvokeMethod("Modify", inParams, null)["RR"].ToString()), null)));
            }
            catch (ManagementException me)
            {
                throw new WMIException(me);
            }
        }
Beispiel #13
0
        public static IPCity GetIpCity(string clientIp)
        {
            int intip = IPHelper.ToInt(clientIp);
            var store = GetStore();

            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();
            var total = GetStoreCount().get("count");
            Func <int, IPCity> getData = delegate(int index)
            {
                return(store.get(index));
            };
            //todo: it will search more than one thousand times which is  Worst condition.
            var model = BinarySearch(intip, total, 0, total - 1, getData);

            //index will search more than one million times(can't find better index for search)
            //combine index is not available
            //var model = store.Where(o => o.Begin <= intip && o.End >= intip)
            //    .FirstOrDefault();
            stopwatch.Stop();
            TimeSpan ts          = stopwatch.Elapsed;
            string   elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:000}",
                                                 ts.Hours, ts.Minutes, ts.Seconds,
                                                 ts.Milliseconds);

            return(model as IPCity);
        }
Beispiel #14
0
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="Data">用户数据组</param>
        /// <returns></returns>
        public bool Register(bk_user Data, string CodeToken)
        {
            DxCsharpSDK.Captcha         captcha  = new DxCsharpSDK.Captcha(appId, appSecret);
            DxCsharpSDK.CaptchaResponse response = captcha.VerifyToken(CodeToken);
            //确保验证状态是SERVER_SUCCESS,SDK中有容错机制,在网络出现异常的情况会返回通过
            if (!response.result)
            {
                return(false);
            }

            IQueryable <bk_user> Us;

            Us = db.UserDAL.QueryUser(Data.Us_UserName, "Us_UserName");
            if (Us.Count() >= 1)
            {
                return(false);
            }
            //设置注册时间
            Data.Us_RegisterTime = DateTime.Now.ToLocalTime();
            //对密码使用MD5加密
            Data.Us_PassWord = MD5Helper.getMD5String(Data.Us_PassWord);
            //取Ip地址
            Data.Us_Ip = IPHelper.GetExternalIp();
            //置头像
            Data.Us_ProfilePhoto = "M_Tx";
            if (Data.Us_NickName == null)
            {
                Data.Us_NickName = Data.Us_UserName;
            }
            //交给数据访问层写入数据库
            db.UserDAL.addUser(Data);
            db.saveChanges();//一键确认数据
            return(true);
        }
Beispiel #15
0
        public static string GetRandomSettingUA()
        {
            var proxyUrl = "";

            if (NodeConfigurationSection.Standalone)
            {
                proxyUrl = ConfigurationManager.AppSettings["RuiJiServer"];
            }
            else
            {
                proxyUrl = ProxyManager.Instance.Elect(NodeProxyTypeEnum.FEEDPROXY);
            }

            if (string.IsNullOrEmpty(proxyUrl))
            {
                throw new Exception("get feedjobs: proxyUrl can't be null");
            }

            proxyUrl = IPHelper.FixLocalUrl(proxyUrl);

            var client      = new RestClient("http://" + proxyUrl);
            var restRequest = new RestRequest("api/setting/ua/random");

            restRequest.Method  = Method.GET;
            restRequest.Timeout = 15000;

            var restResponse = client.Execute(restRequest);

            return(restResponse.Content);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string ip = IPHelper.GetIP();
                try
                {
                    string   userInfo = EnterPrise_Server.GetSelfInfo(this.Request);
                    UserInfo userIn   = JsonConvert.DeserializeObject <UserInfo>(userInfo);
                    hid_Name.Value  = userIn.name;   //userIn.name;
                    hid_Phone.Value = userIn.mobile; // userIn.mobile;
                    LogHelper.Info("登陆方式:" + GetUserAgent() + "   登陆时间:" + System.DateTime.Now.ToString() + "   登陆IP:" + ip + "   登陆信息:" + userIn.name + ":" + userIn.mobile);
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                }
                if (string.IsNullOrWhiteSpace(hid_Name.Value) || string.IsNullOrWhiteSpace(hid_Phone.Value))
                {
                    hid_Name.Value  = "一号位";         //userIn.name;
                    hid_Phone.Value = "13000000000"; // userIn.mobile;
                    LogHelper.Info("登陆方式:" + GetUserAgent() + "   登陆时间:" + System.DateTime.Now.ToString() + "   登陆IP:" + ip + "   登陆信息:" + hid_Name.Value + ":13000000000");
                }
                //hid_Name.Value = "关业龙";//userIn.name;
                //hid_Phone.Value = "13031190350";// userIn.mobile;

                //hid_Name.Value = "ttm";//userIn.name;
                //hid_Phone.Value = "21313213";// userIn.mobile;

                //hid_Name.Value = "刘泽";//userIn.name;
                //hid_Phone.Value = "13716753217";// userIn.mobile;
            }
        }
Beispiel #17
0
        public ActionResult LogOut(string fromController, string fromAction, string fromId)
        {
            var login = (AccountViewModels)Session["GHLogin"];

            if (login != null)
            {
                var    userHostAddress = Request.UserHostAddress;
                var    xForwardedFor   = Request.ServerVariables["X_FORWARDED_FOR"];
                string ip = IPHelper.GetClientIpAddress(userHostAddress, xForwardedFor);
            }

            Session.RemoveAll();

            string redirectUrl = "";

            if (!TempData.ContainsKey("RedirectUrl"))
            {
                redirectUrl = string.Format("/{0}/{1}", fromController, fromAction);
                if (!string.IsNullOrEmpty(fromId))
                {
                    redirectUrl = string.Concat(redirectUrl, "/", fromId);
                }
                TempData["RedirectUrl"] = redirectUrl;
            }

            return(RedirectToAction("Login", "Account"));
        }
Beispiel #18
0
        private async Task <JwtSecurityToken> GenerateJWToken(ApplicationUser user)
        {
            var userClaims = await _userManager.GetClaimsAsync(user);

            var roles = await _userManager.GetRolesAsync(user);

            var roleClaims = new List <Claim>();

            for (int i = 0; i < roles.Count; i++)
            {
                roleClaims.Add(new Claim("roles", roles[i]));
            }
            string ipAddress = IPHelper.GetIpAddress();
            var    claims    = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Email, user.Email),
                new Claim("uid", user.Id),
                new Claim("ip", ipAddress)
            }
            .Union(userClaims)
            .Union(roleClaims);
            var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.Key));
            var signingCredentials   = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);
            var jwtSecurityToken     = new JwtSecurityToken(
                issuer: _jwtSettings.Issuer,
                audience: _jwtSettings.Audience,
                claims: claims,
                expires: DateTime.UtcNow.AddMinutes(_jwtSettings.DurationInMinutes),
                signingCredentials: signingCredentials);

            return(jwtSecurityToken);
        }
Beispiel #19
0
        /// <summary>
        /// The run service.
        /// </summary>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        protected override bool RunService()
        {
            var bannedIPs = this.DataCache.GetOrSet(
                Constants.Cache.BannedIP,
                () => this.BannedIpRepository.Get(x => x.BoardID == BoardContext.Current.PageBoardID).Select(x => x.Mask.Trim()).ToList());

            var ipToCheck = this.HttpRequestBase.ServerVariables["REMOTE_ADDR"];

            // check for this user in the list...
            if (bannedIPs == null || !bannedIPs.Any(row => IPHelper.IsBanned(row, ipToCheck)))
            {
                return(true);
            }

            if (BoardContext.Current.BoardSettings.LogBannedIP)
            {
                this.Logger.Log(
                    null,
                    "Banned IP Blocked",
                    $@"Ending Response for Banned User at IP ""{ipToCheck}""",
                    EventLogTypes.IpBanDetected);
            }

            if (Config.BannedIpRedirectUrl.IsSet())
            {
                this.HttpResponseBase.Redirect(Config.BannedIpRedirectUrl);
            }

            this.HttpResponseBase.End();

            return(false);
        }
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            string controllerName = filterContext.RouteData.Values["controller"].ToString().ToLower();
            string actionName     = filterContext.RouteData.Values["action"].ToString().ToLower();
            var    admin          = PersonalFramework.Service.AdminLoginHelper.CurrentUser();

            //记录操作日志,写进操作日志中
            var log = new ActionLog();

            log.ActionContent = "";
            log.CreateTime    = DateTime.Now;
            log.IP            = IPHelper.GetClientIp();
            log.Location      = controllerName + "/" + actionName;
            log.RequestData   = Request.Form.ToString();
            log.Platform      = "后台";
            log.Source        = Request.HttpMethod;
            log.RequestUrl    = Request.Url.AbsoluteUri;
            if (admin != null)
            {
                log.UID      = admin.ID;
                log.UserName = admin.AdminName;
            }
            context.ActionLog.Add(log);
            //context.SaveChanges();

            if (Request.UrlReferrer != null)
            {
                ViewBag.FormUrl = Request.UrlReferrer.ToString();
            }
        }
Beispiel #21
0
        /// <summary>
        /// 新增日志
        /// </summary>
        /// <param name="remark"></param>
        public void AddLog(string remark = "")
        {
            try
            {
                var httpContext = CatContext.HttpContext;

                Sys_HttpRequest_Log entity = new Sys_HttpRequest_Log()
                {
                    TraceIdentifier = httpContext.TraceIdentifier,
                    Host            = httpContext.Request.Host.ToString(),
                    Path            = httpContext.Request.Path,
                    Method          = httpContext.Request.Method,
                    Url             = httpContext.Request.Scheme + "://" + httpContext.Request.Host + httpContext.Request.Path + httpContext.Request.QueryString,
                    Referer         = httpContext.Request.Headers["Referer"].ToStr(),
                    ContentType     = httpContext.Request.ContentType,
                    RequestParams   = RequestHelper.GetParms(httpContext.Request),
                    User_Agent      = httpContext.Request.Headers["User-Agent"].ToStr(),
                    RemoteIpAddress = IPHelper.GetClientIP(),
                    Remark          = remark,
                };

                entity.Create_Time = entity.Create_Time ?? DateTime.Now;
                base.InsertOne(entity);
            }
            catch (Exception ex)
            {
                FileHelper.CreateFiles($"~/log/exception/Sys_HttpRequest_Log.{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.log", ex);
            }
        }
Beispiel #22
0
        async void timer_Tick(object sender, EventArgs e)
        {
            if (running)
            {
                return;
            }

            running = true;

            await Task.Run(() =>
            {
                // Resets the WMI cache (used for non admin users)
                Connection.LocalOwnerWMICache = null;
                foreach (var c in IPHelper.GetAllConnections())
                {
                    Dispatcher.Invoke(() => AddOrUpdateConnection(c));
                }

                for (int i = lstConnections.Count - 1; i >= 0; i--)
                {
                    var item       = lstConnections[i];
                    double elapsed = DateTime.Now.Subtract(item.LastSeen).TotalSeconds;
                    if (elapsed > ConnectionTimeoutRemove)
                    {
                        Dispatcher.Invoke(() => lstConnections.Remove(item));
                    }
                    else if (elapsed > ConnectionTimeoutDying)
                    {
                        item.IsDying = true;
                    }
                }
            }).ConfigureAwait(false);

            running = false;
        }
Beispiel #23
0
        /// <summary>
        /// The run service.
        /// </summary>
        /// <returns>
        /// The run service.
        /// </returns>
        protected override bool RunService()
        {
            // TODO: The data cache needs a more fast string array check as number of banned ips can be huge, but current output is too demanding on perfomance in the cases.
            var bannedIPs = this.DataCache.GetOrSet(
                Constants.Cache.BannedIP,
                () => this.BannedIpRepository.Get(x => x.BoardID == BoardContext.Current.PageBoardID).Select(x => x.Mask.Trim()).ToList());

            var ipToCheck = this.HttpRequestBase.ServerVariables["REMOTE_ADDR"];

            // check for this user in the list...
            if (bannedIPs == null || !bannedIPs.Any(row => IPHelper.IsBanned(row, ipToCheck)))
            {
                return(true);
            }

            if (BoardContext.Current.Get <BoardSettings>().LogBannedIP)
            {
                this.Logger.Log(
                    null,
                    "Banned IP Blocked",
                    $@"Ending Response for Banned User at IP ""{ipToCheck}""",
                    EventLogTypes.IpBanDetected);
            }

            if (Config.BannedIpRedirectUrl.IsSet())
            {
                this.HttpResponseBase.Redirect(Config.BannedIpRedirectUrl);
            }

            this.HttpResponseBase.End();

            return(false);
        }
        private async Task <JwtSecurityToken> GenerateJWToken(ApplicationUser user)
        {
            var userClaims = await _userManager.GetClaimsAsync(user);

            var roles = await _userManager.GetRolesAsync(user);

            var roleClaims = new List <Claim>();

            for (int i = 0; i < roles.Count; i++)
            {
                roleClaims.Add(new Claim("roles", roles[i]));
            }
            string ipAddress = IPHelper.GetIpAddress();
            var    claims    = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Email, user.Email),
                new Claim("uid", user.Id),
                new Claim("ip", ipAddress)
            }
            .Union(userClaims)
            .Union(roleClaims);

            return(JWTGeneration(claims));
        }
Beispiel #25
0
 private void FrmMain_Load(object sender, EventArgs e)
 {
     cbDrives.Items.AddRange(DiskHelper.GetAllDiskName());
     cbOstype.Items.AddRange(OsTypes);
     tbIP.Text = IPHelper.GetAddressIPFromKeys(configs.Select(c => c.ip).ToList());
     InitDefault();
 }
Beispiel #26
0
        public IActionResult Save(cms_ip_manager dto)
        {
            if (!IPHelper.IsIP(dto.start_ip))
            {
                return(Error("起始IP地址错误"));
            }
            if (!IPHelper.IsIP(dto.end_ip))
            {
                return(Error("结束IP地址错误"));
            }
            dto.start_ip_val = IPHelper.IPValue(dto.start_ip);
            dto.end_ip_val   = IPHelper.IPValue(dto.end_ip);
            long id = _ipManagerApp.SaveData(dto, RequestHelper.AdminInfo());

            if (id > 0)
            {
                dto.id = (int)id;
                if (dto.limit_enable == DataStatusConstant.ENABLE)
                {
                    IPHelper.AddIpRange(dto);
                }
            }
            else
            {
                if (dto.limit_enable == DataStatusConstant.ENABLE)
                {
                    IPHelper.AddIpRange(dto);
                }
                else
                {
                    IPHelper.RemoveIpRange(dto.id);
                }
            }
            return(Success("保存成功"));
        }
Beispiel #27
0
        public void ToIpEndPointTest()
        {
            var a = IPHelper.ToIpEndPoint("127.0.0.1,123");

            Assert.AreEqual("127.0.0.1", a.Address.ToString());
            Assert.AreEqual(123, a.Port);
        }
Beispiel #28
0
        void timer_Tick(object sender, EventArgs e)
        {
            foreach (var c in IPHelper.GetAllConnections(true)
                     .Where(co => co.State == IPHelper.MIB_TCP_STATE.ESTABLISHED && !co.IsLoopback && co.OwnerModule != null))
            {
                AddOrUpdateConnection(c);
            }

            CurrentMap.UpdateLayout();

            /*
             * var killduration = Math.Max(5, 3 * _interval);
             * var dieduration = Math.Max(2, 2 * _interval);
             * for (int i = Connections.Count - 1; i >= 0; i--)
             * {
             *  var item = Connections[i];
             *  double elapsed = DateTime.Now.Subtract(item.LastSeen).TotalSeconds;
             *  if (elapsed > killduration)
             *  {
             *      Connections.Remove(item);
             *  }
             *  else if (elapsed > dieduration)
             *  {
             *      item.IsDying = true;
             *  }
             * }*/
        }
        private void button_Start_Click(object sender, RoutedEventArgs e)
        {
            //根据当前设置的开始和结束IP来计算总大小
            string[] strstart = textbox_StartIP.Text.Split('.');
            string[] strend   = textbox_EndIP.Text.Split('.');

            if (strstart.Length != 3 && strend.Length != 3)
            {
                return;
            }

            if (strstart.Length == 3 && strend.Length == 3)
            {
                //sum = (Convert.ToInt32(strend[0]) * Convert.ToInt32(strend[1]) * Convert.ToInt32(strend[2]))
                //    - (Convert.ToInt32(strstart[0]) * Convert.ToInt32(strstart[1]) * Convert.ToInt32(strstart[2]));
                sum = IPHelper.IpToInt(textbox_EndIP.Text + ".0")
                      - IPHelper.IpToInt(textbox_StartIP.Text + ".0");
            }

            //点击开始,后台进行IP地址验证并循环插入数据库操作
            bgw = new BackgroundWorker();

            bgw.DoWork += Bgw_DoWork;
            bgw.WorkerReportsProgress      = true;
            bgw.WorkerSupportsCancellation = true;
            bgw.ProgressChanged           += Bgw_ProgressChanged;
            bgw.RunWorkerAsync(new string[] { textbox_StartIP.Text, textbox_EndIP.Text });
        }
Beispiel #30
0
        public void GetIPAddressesTest()
        {
            var ipStr = "192.168.0.188";
            var ip    = IPHelper.GetLocalIPAddress();

            Assert.AreEqual(ipStr, ip.ToString());
        }