首頁  >  文章  >  後端開發  >  C#取得IP及判斷IP是否在區間的範例程式碼

C#取得IP及判斷IP是否在區間的範例程式碼

黄舟
黄舟原創
2017-03-22 11:46:141760瀏覽

本文主要介紹了C# 取得IP及判斷IP是否在區間的方法。具有很好的參考價值,以下跟著小編一起來看下吧

話不多說,請看程式碼:

/// <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(&#39;-&#39;);
    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(&#39;.&#39;);
    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(&#39;.&#39;);
    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;
  }

以上是C#取得IP及判斷IP是否在區間的範例程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn