This paper mainly introduces the method of acquiring IP in C # and judging whether IP is in interval. Have a good reference value, follow the small series together to see it
If you don't say much, look at the code:
<summary>///Get client IP///</summary>//<returns></returns> public static string Getclien Tipaddress () {var HttpContext = HttpContext.Current; if (httpContext.Request.ServerVariables = = null) {return null; } var clientip = httpcontext.request.servervariables["Http_x_forwarded_for"]?? httpcontext.request.servervariables["REMOTE_ADDR"]; try {foreach (var hostaddress in dns.gethostaddresses (ClientIP)) {if (hostaddress.addressfam ily = = addressfamily.internetwork) {return hostaddress.tostring (); }} foreach (Var hostaddress in dns.gethostaddresses (Dns.gethostname ())) {if (HOSTADDRESS.A ddressfamily = = addressfamily.internetwork) {return hostaddress.tostring (); }}} catch (Exception ex) {} return clientip; }///<summary>//IP is within the IP space </summary>//<param name= "IP" ></param>//<param name= "ipsection" ></param>//&L t;returns></returns> public static Boolean ipexistsinrange (string IP, String ipsection) {ipsection = Ipsect Ion. Trim (); ip = IP. Trim (); int idx = ipsection.indexof ('-'); String Beginip = ipsection.substring (0, IDX); String EndIP = ipsection.substring (idx + 1); Return Getip2long (Beginip) <= getip2long (IP) && getip2long (IP) <= getip2long (ENDIP); } public static long Getip2long (String IP) {ip = IP. Trim (); string[] ips = IP. Split ('. '); Long Ip2long = 0L; for (int i = 0; i < 4; ++i) {Ip2long = Ip2long << 8 | Int64.parse (Ips[i]); } return Ip2long; } public static long getip2long2 (String IP) {ip = IP. Trim (); string[] ips = IP. Split ('. '); Long ip1 = Int64.parse (Ips[0]); Long ip2 = Int64.parse (ips[1]); Long IP3 = Int64.parse (ips[2]); Long IP4 = Int64.parse (ips[3]); LonG Ip2long = 1L * IP1 * * * * * * * * * * * * + IP2 * * * * * * + IP3 * + ip4; return ip2long; }