.net获取客户端IP

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// WebUtils 的摘要说明
/// </summary>
public class WebUtils
{
    /// <summary>
    /// 得到客户端IP
    /// </summary>
    /// <param name="httpRequest"></param>
    /// <returns></returns>
    public static string GetCilentIP(HttpRequest httpRequest)
    {
        string localIP = "";
        string strIPAddr = "";

        try
        {
            //一、没有使用代理服务器的情况:
            //REMOTE_ADDR = 您的 IP
            //HTTP_VIA = 没数值或不显示
            //HTTP_X_FORWARDED_FOR = 没数值或不显示
            //二、使用透明代理服务器的情况:
            //REMOTE_ADDR = 代理服务器 IP
            //HTTP_VIA = 代理服务器 IP
            //HTTP_X_FORWARDED_FOR = 您的真实 IP

            string HTTP_X_FORWARDED_FOR = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            string REMOTE_ADDR = HttpContext.Current.Request.ServerVariables["Remote_Addr"];

            if (string.IsNullOrEmpty(HTTP_X_FORWARDED_FOR) || HTTP_X_FORWARDED_FOR.IndexOf("unknown") >= 0)
            {
                strIPAddr = REMOTE_ADDR;
            }
            else if (HTTP_X_FORWARDED_FOR.IndexOf(",") >= 0)
            {
                strIPAddr = HTTP_X_FORWARDED_FOR.ToString().Split(',')[0].Trim();
            }
            else
            {
                strIPAddr = HTTP_X_FORWARDED_FOR;
            }
            localIP = strIPAddr;
            if (strIPAddr == "::1")
            {
                localIP = "127.0.0.1";
            }
        }
        catch (Exception )
        {
            return "";
        }

        return localIP;
    }
}

  

posted @ 2017-10-20 10:36  jiftle  阅读(438)  评论(0编辑  收藏  举报