Exemple de code C# pour obtenir l'adresse IP et déterminer si l'adresse IP est à portée

黄舟
Libérer: 2017-03-22 11:46:14
original
1728 Les gens l'ont consulté

Cet article présente principalement la méthode C# pour obtenir l'IP et déterminer si l'IP est dans la plage. Il a une très bonne valeur de référence, jetons un oeil avec l'éditeur ci-dessous

Sans plus attendre, jetez un oeil au code :

/// <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;
  }
Copier après la connexion

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!