一直在獲取ip地址,獲取IP及判斷IP是否在區間

 2023-11-19 阅读 17 评论 0

摘要:/// <summary>/// 獲取客戶端IP/// </summary>/// <returns></returns>public static string GetClientIpAddress(){var httpContext = HttpContext.Current;if (httpContext.Request.ServerVariables == null){return null;}var client
    /// <summary>/// 獲取客戶端IP/// </summary>/// <returns></returns>public static string GetClientIpAddress(){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.AddressFamily == AddressFamily.InterNetwork){return hostAddress.ToString();}}foreach (var hostAddress in Dns.GetHostAddresses(Dns.GetHostName())){if (hostAddress.AddressFamily == AddressFamily.InterNetwork){return hostAddress.ToString();}}}catch (Exception ex){}return clientIp;}/// <summary>/// ip是否在ip空間內/// </summary>/// <param name="ip"></param>/// <param name="ipSection"></param>/// <returns></returns>public static Boolean ipExistsInRange(String ip, String ipSection){ipSection = ipSection.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 * 256 * 256 * 256 + ip2 * 256 * 256 + ip3 * 256 + ip4;return ip2long;}

?

轉載于:https://www.cnblogs.com/MrZheng/p/6407873.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/180164.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息