C# 获取IP及判断IP是否在区间
话不多说,请看代码:
///<summary> ///获取客户端IP ///</summary> ///<returns></returns> publicstaticstringGetClientIpAddress() { varhttpContext=HttpContext.Current; if(httpContext.Request.ServerVariables==null) { returnnull; } varclientIp=httpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]??httpContext.Request.ServerVariables["REMOTE_ADDR"]; try { foreach(varhostAddressinDns.GetHostAddresses(clientIp)) { if(hostAddress.AddressFamily==AddressFamily.InterNetwork) { returnhostAddress.ToString(); } } foreach(varhostAddressinDns.GetHostAddresses(Dns.GetHostName())) { if(hostAddress.AddressFamily==AddressFamily.InterNetwork) { returnhostAddress.ToString(); } } } catch(Exceptionex) { } returnclientIp; } ///<summary> ///ip是否在ip空间内 ///</summary> ///<paramname="ip"></param> ///<paramname="ipSection"></param> ///<returns></returns> publicstaticBooleanipExistsInRange(Stringip,StringipSection) { ipSection=ipSection.Trim(); ip=ip.Trim(); intidx=ipSection.IndexOf('-'); StringbeginIP=ipSection.Substring(0,idx); StringendIP=ipSection.Substring(idx+1); returngetIp2long(beginIP)<=getIp2long(ip)&&getIp2long(ip)<=getIp2long(endIP); } publicstaticlonggetIp2long(Stringip) { ip=ip.Trim(); String[]ips=ip.Split('.'); longip2long=0L; for(inti=0;i<4;++i) { ip2long=ip2long<<8|Int64.Parse(ips[i]); } returnip2long; } publicstaticlonggetIp2long2(Stringip) { ip=ip.Trim(); String[]ips=ip.Split('.'); longip1=Int64.Parse(ips[0]); longip2=Int64.Parse(ips[1]); longip3=Int64.Parse(ips[2]); longip4=Int64.Parse(ips[3]); longip2long=1L*ip1*256*256*256+ip2*256*256+ip3*256+ip4; returnip2long; }
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!