C# 获取Ip地址

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/My_ben/article/details/83931720

获取Ip地址,代码如下:

public static string GetIp()
{
   string ip = string.Empty;
   HttpContext context = HttpContext.Current;
   if (context != null)
   {
      HttpRequest request = context.Request;
      ip = request.Headers["HTTP_X_FORWARDED_FOR"];//微信相关特殊处理,@刘俊
      if (string.IsNullOrEmpty(ip) || (ip.ToLower() == "unknown"))
      {
          ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
          if (string.IsNullOrEmpty(ip) || (ip.ToLower() == "unknown"))
          {
              ip = request.ServerVariables["HTTP_X_REAL_IP"];
              if (string.IsNullOrEmpty(ip))
              {
                   ip = request.ServerVariables["REMOTE_ADDR"];
               }
           }
       }
    }
    return GetShortIp(ip);
}

猜你喜欢

转载自blog.csdn.net/My_ben/article/details/83931720