栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

C# 获取IP及判断IP是否在区间

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C# 获取IP及判断IP是否在区间

话不多说,请看代码:

/// 
  /// 获取客户端IP
  /// 
  /// 
  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;
    }
  /// 
  /// ip是否在ip空间内
  /// 
  /// 
  /// 
  /// 
  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;
  }

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持考高分网!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/123638.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号