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

來源:互聯網
上載者:User
本文主要介紹了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('-');    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;  }
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.