当前位置: 移动技术网 > IT编程>开发语言>c# > C# 获取IP及判断IP是否在区间

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

话不多说,请看代码:

/// <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;
  }

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网