c#获取客户端IP为何得到的值是服务器IP地址

时间:2021-01-23 16:13:04
1.string struserIP = System.Web.HttpContext.Current.Request.UserHostAddress
2.        private string GetClientIP()
        {
            string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }
            return result;
        }
得到的数据是服务器内网的IP地址,为何?2种方式得到的值是一样。
哪位朋友知道,不胜感激。

24 个解决方案

#1


在哪测试的?

#2


to:only_endure 
让其他公司的以前的同事测试的。

#3


在另外的一个公司之前的同事测试的,登录后保存的IP信息发现是我服务的内网的IP地址。

#4


result不是公有静态变量吧?

#5


服务器是通过DNS中转的,得到的是服务器DNS的内网IP地址。
为何获取不了客户端的IP。

#6


Request.ServerVariables("Url") 
返回服务器地址

Request.ServerVariables("Path_Info") 
客户端提供的路径信息

Request.ServerVariables("Appl_Physical_Path") 
与应用程序元数据库路径相应的物理路径

Request.ServerVariables("Path_Translated") 
通过由虚拟至物理的映射后得到的路径

Request.ServerVariables("Script_Name") 
执行脚本的名称

Request.ServerVariables("Query_String") 
查询字符串內容

Request.ServerVariables("Http_Referer") 
请求的字符串內容

Request.ServerVariables("Server_Port") 
接受请求的服务器端口号

Request.ServerVariables("Remote_Addr") 
发出请求的远程主机的IP地址

Request.ServerVariables("Remote_Host") 
发出请求的远程主机名称

Request.ServerVariables("Local_Addr") 
返回接受请求的服务器地址

Request.ServerVariables("Http_Host") 
返回服务器地址

Request.ServerVariables("Server_Name") 
服务器的主机名、DNS地址或IP地址

Request.ServerVariables("Request_Method") 
提出请求的方法比如GET、HEAD、POST等等

Request.ServerVariables("Server_Port_Secure")
如果接受请求的服务器端口为安全端口时,则为1,否则为0

Request.ServerVariables("Server_Protocol")
服务器使用的协议的名称和版本

Request.ServerVariables("Server_Software")
应答请求并运行网关的服务器软件的名称和版本

Request.ServerVariables("All_Http")
客户端发送的所有HTTP标头,前缀HTTP_

Request.ServerVariables("All_Raw")
客户端发送的所有HTTP标头,其结果和客户端发送时一样,没有前缀HTTP_

Request.ServerVariables("Appl_MD_Path")
应用程序的元数据库路径

Request.ServerVariables("Content_Length")
客户端发出內容的长度

Request.ServerVariables("Https")
如果请求穿过安全通道(SSL),则返回ON如果请求来自非安全通道,则返回OFF

Request.ServerVariables("Instance_ID")
IIS实例的ID号

Request.ServerVariables("Instance_Meta_Path")
响应请求的IIS实例的元数据库路径

Request.ServerVariables("Http_Accept_Encoding")
返回內容如:gzip,deflate

Request.ServerVariables("Http_Accept_Language")
返回內容如:en-us

Request.ServerVariables("Http_Connection")
返回內容:Keep-Alive

Request.ServerVariables("Http_Cookie")

Request.ServerVariables("Http_User_Agent")
返回內容:Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1)

Request.ServerVariables("Https_Keysize")
安全套接字层连接关键字的位数,如128

Request.ServerVariables("Https_Secretkeysize")
服务器验证私人关键字的位数如1024

Request.ServerVariables("Https_Server_Issuer")
服务器证书的发行者字段

Request.ServerVariables("Https_Server_Subject")
服务器证书的主题字段

Request.ServerVariables("Auth_Password")
当使用基本验证模式时,客户在密码对话框中输入的密码

Request.ServerVariables("Auth_Type")
是用户访问受保护的脚本时,服务器用於检验用户的验证方法

Request.ServerVariables("Auth_User")
代证的用户名

Request.ServerVariables("Cert_Cookie")
唯一的客户证书ID号

Request.ServerVariables("Cert_Flag")
客户证书标誌,如有客户端证书,则bit0为0如果客户端证书验证无效,bit1被设置为1

Request.ServerVariables("Cert_Issuer")
用户证书中的发行者字段

Request.ServerVariables("Cert_Keysize")
安全套接字层连接关键字的位数,如128

Request.ServerVariables("Cert_Secretkeysize")
服务器验证私人关键字的位数如1024

Request.ServerVariables("Cert_Serialnumber")
客户证书的序列号字段

Request.ServerVariables("Cert_Server_Issuer")
服务器证书的发行者字段

Request.ServerVariables("Cert_Server_Subject")
服务器证书的主题字段

Request.ServerVariables("Cert_Subject")
客户端证书的主题字段

Request.ServerVariables("Content_Type")
客户发送的form內容或HTTPPUT的数据类型


#7


你是在哪写的?context参数传递了吗?

#8


用户登录的时候获取的,context参数指的是什么?

#9


是不是写在类似label标签里的?显示就这样?你把代码再帖全些看看。

#10


看下iis的日志是否客户端也是这个地址

#11


iis日志里记录的没有一个外网访问的记录,显示的是内网的IP地址。
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string struserIP = System.Web.HttpContext.Current.Request.UserHostAddress;
            string strUserName = this.txtUserName.Text.ToString();
            string strPassWord = this.txtPassWord.Text.ToString();

            LoginSys tmp = new LoginSys(strUserName, strPassWord,struserIP);
            if (tmp.Pass)
            {
//
            }
        }

#12


我觉得你的获取IP如果是写在类里面的,页面调用该类时,至少要传递个HttpContext参数吧,因为在类中是捕获不到的。

#13


struserIP不是已经得到值了吗?直接传到相应的数据处理类。

#14


引用 11 楼 jinseyd 的回复:
iis日志里记录的没有一个外网访问的记录,显示的是内网的IP地址。 

C# code        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string struserIP = System.Web.HttpContext.Current.Request.UserHostAddress;
            string strUserName = this.txtUserName.Text.ToString();
            string strPassWord = this.txtPassWord.Text.ToString();

            LoginSys…


显然用户不是直接访问web服务的,大概经过内网其它机器的转发

#15


楼主莫非是用的webservice,如果是这样,客户端请求可都是你的服务器在请求了。

#16


TO:牙神幻十郎
是通过内网DNS服务器转发的,所以获取的是DNS服务的内网IP,请问可以设置吗?

#17


这需要转发服务支持HTTP_X_FORWARDED_FOR

#18


帮你顶

#19


大概是要在DNS里設置,哪个朋友知道怎么设置吗?
网上找到的一段代码,如下,还是不能获取,得到的IP是DNS服务器的内网IP。
/// <summary> 
        /// 取得客户端真实IP。如果有代理则取第一个非内网地址 
        /// </summary> 
        public static string IPAddress
        {
            get
            {
                string result = String.Empty;

                result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (result != null && result != String.Empty)
                {
                    //可能有代理 
                    if (result.IndexOf(".") == -1)    //没有“.”肯定是非IPv4格式 
                        result = null;
                    else
                    {
                        if (result.IndexOf(",") != -1)
                        {
                            //有“,”,估计多个代理。取第一个不是内网的IP。 
                            result = result.Replace(" ", "").Replace("'", "");
                            string[] temparyip = result.Split(",;".ToCharArray());
                            for (int i = 0; i < temparyip.Length; i++)
                            {
                                if (IsIPAddress(temparyip[i])
                                    && temparyip[i].Substring(0, 3) != "10."
                                    && temparyip[i].Substring(0, 7) != "192.168"
                                    && temparyip[i].Substring(0, 7) != "172.16.")
                                {
                                    return temparyip[i];    //找到不是内网的地址 
                                }
                            }
                        }
                        else if (IsIPAddress(result)) //代理即是IP格式 
                            return result;
                        else
                            result = null;    //代理中的内容 非IP,取IP 
                    }

                }

                string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null
                    && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty)
                    ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
                    : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                if (null == result || result == String.Empty)
                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                if (result == null || result == String.Empty)
                    result = HttpContext.Current.Request.UserHostAddress;

                return result;
            }
        }
        /// <summary>
        /// 判断是否是IP地址格式 0.0.0.0
        /// </summary>
        /// <param name="str1">待判断的IP地址</param>
        /// <returns>true or false</returns>
        public static bool IsIPAddress(string str1)
        {
            if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15)
                return false;

            string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";

            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
            return regex.IsMatch(str1);
        }

#20


 问题被人遗忘了,自己顶一下!

#21


已经解决,是ISA防火墙设置问题。
http://www.cnblogs.com/cnaspnet/archive/2008/07/05/1236181.html

#22


楼主,我也碰到一样的问题,可是我对ISA的设置不太熟悉,能否将ISA的设置列详细点,以供大家参考,谢谢!

#23


引用 6 楼 only_endure 的回复:
Request.ServerVariables("Url") 
返回服务器地址

Request.ServerVariables("Path_Info") 
客户端提供的路径信息

Request.ServerVariables("Appl_Physical_Path") 
与应用程序元数据库路径相应的物理路径

Request.ServerVariables("Path_Tra……
不错

#24


我现在遇到了同样的问题,但是我没有安装isa防火墙啊

#1


在哪测试的?

#2


to:only_endure 
让其他公司的以前的同事测试的。

#3


在另外的一个公司之前的同事测试的,登录后保存的IP信息发现是我服务的内网的IP地址。

#4


result不是公有静态变量吧?

#5


服务器是通过DNS中转的,得到的是服务器DNS的内网IP地址。
为何获取不了客户端的IP。

#6


Request.ServerVariables("Url") 
返回服务器地址

Request.ServerVariables("Path_Info") 
客户端提供的路径信息

Request.ServerVariables("Appl_Physical_Path") 
与应用程序元数据库路径相应的物理路径

Request.ServerVariables("Path_Translated") 
通过由虚拟至物理的映射后得到的路径

Request.ServerVariables("Script_Name") 
执行脚本的名称

Request.ServerVariables("Query_String") 
查询字符串內容

Request.ServerVariables("Http_Referer") 
请求的字符串內容

Request.ServerVariables("Server_Port") 
接受请求的服务器端口号

Request.ServerVariables("Remote_Addr") 
发出请求的远程主机的IP地址

Request.ServerVariables("Remote_Host") 
发出请求的远程主机名称

Request.ServerVariables("Local_Addr") 
返回接受请求的服务器地址

Request.ServerVariables("Http_Host") 
返回服务器地址

Request.ServerVariables("Server_Name") 
服务器的主机名、DNS地址或IP地址

Request.ServerVariables("Request_Method") 
提出请求的方法比如GET、HEAD、POST等等

Request.ServerVariables("Server_Port_Secure")
如果接受请求的服务器端口为安全端口时,则为1,否则为0

Request.ServerVariables("Server_Protocol")
服务器使用的协议的名称和版本

Request.ServerVariables("Server_Software")
应答请求并运行网关的服务器软件的名称和版本

Request.ServerVariables("All_Http")
客户端发送的所有HTTP标头,前缀HTTP_

Request.ServerVariables("All_Raw")
客户端发送的所有HTTP标头,其结果和客户端发送时一样,没有前缀HTTP_

Request.ServerVariables("Appl_MD_Path")
应用程序的元数据库路径

Request.ServerVariables("Content_Length")
客户端发出內容的长度

Request.ServerVariables("Https")
如果请求穿过安全通道(SSL),则返回ON如果请求来自非安全通道,则返回OFF

Request.ServerVariables("Instance_ID")
IIS实例的ID号

Request.ServerVariables("Instance_Meta_Path")
响应请求的IIS实例的元数据库路径

Request.ServerVariables("Http_Accept_Encoding")
返回內容如:gzip,deflate

Request.ServerVariables("Http_Accept_Language")
返回內容如:en-us

Request.ServerVariables("Http_Connection")
返回內容:Keep-Alive

Request.ServerVariables("Http_Cookie")

Request.ServerVariables("Http_User_Agent")
返回內容:Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1)

Request.ServerVariables("Https_Keysize")
安全套接字层连接关键字的位数,如128

Request.ServerVariables("Https_Secretkeysize")
服务器验证私人关键字的位数如1024

Request.ServerVariables("Https_Server_Issuer")
服务器证书的发行者字段

Request.ServerVariables("Https_Server_Subject")
服务器证书的主题字段

Request.ServerVariables("Auth_Password")
当使用基本验证模式时,客户在密码对话框中输入的密码

Request.ServerVariables("Auth_Type")
是用户访问受保护的脚本时,服务器用於检验用户的验证方法

Request.ServerVariables("Auth_User")
代证的用户名

Request.ServerVariables("Cert_Cookie")
唯一的客户证书ID号

Request.ServerVariables("Cert_Flag")
客户证书标誌,如有客户端证书,则bit0为0如果客户端证书验证无效,bit1被设置为1

Request.ServerVariables("Cert_Issuer")
用户证书中的发行者字段

Request.ServerVariables("Cert_Keysize")
安全套接字层连接关键字的位数,如128

Request.ServerVariables("Cert_Secretkeysize")
服务器验证私人关键字的位数如1024

Request.ServerVariables("Cert_Serialnumber")
客户证书的序列号字段

Request.ServerVariables("Cert_Server_Issuer")
服务器证书的发行者字段

Request.ServerVariables("Cert_Server_Subject")
服务器证书的主题字段

Request.ServerVariables("Cert_Subject")
客户端证书的主题字段

Request.ServerVariables("Content_Type")
客户发送的form內容或HTTPPUT的数据类型


#7


你是在哪写的?context参数传递了吗?

#8


用户登录的时候获取的,context参数指的是什么?

#9


是不是写在类似label标签里的?显示就这样?你把代码再帖全些看看。

#10


看下iis的日志是否客户端也是这个地址

#11


iis日志里记录的没有一个外网访问的记录,显示的是内网的IP地址。
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string struserIP = System.Web.HttpContext.Current.Request.UserHostAddress;
            string strUserName = this.txtUserName.Text.ToString();
            string strPassWord = this.txtPassWord.Text.ToString();

            LoginSys tmp = new LoginSys(strUserName, strPassWord,struserIP);
            if (tmp.Pass)
            {
//
            }
        }

#12


我觉得你的获取IP如果是写在类里面的,页面调用该类时,至少要传递个HttpContext参数吧,因为在类中是捕获不到的。

#13


struserIP不是已经得到值了吗?直接传到相应的数据处理类。

#14


引用 11 楼 jinseyd 的回复:
iis日志里记录的没有一个外网访问的记录,显示的是内网的IP地址。 

C# code        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string struserIP = System.Web.HttpContext.Current.Request.UserHostAddress;
            string strUserName = this.txtUserName.Text.ToString();
            string strPassWord = this.txtPassWord.Text.ToString();

            LoginSys…


显然用户不是直接访问web服务的,大概经过内网其它机器的转发

#15


楼主莫非是用的webservice,如果是这样,客户端请求可都是你的服务器在请求了。

#16


TO:牙神幻十郎
是通过内网DNS服务器转发的,所以获取的是DNS服务的内网IP,请问可以设置吗?

#17


这需要转发服务支持HTTP_X_FORWARDED_FOR

#18


帮你顶

#19


大概是要在DNS里設置,哪个朋友知道怎么设置吗?
网上找到的一段代码,如下,还是不能获取,得到的IP是DNS服务器的内网IP。
/// <summary> 
        /// 取得客户端真实IP。如果有代理则取第一个非内网地址 
        /// </summary> 
        public static string IPAddress
        {
            get
            {
                string result = String.Empty;

                result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (result != null && result != String.Empty)
                {
                    //可能有代理 
                    if (result.IndexOf(".") == -1)    //没有“.”肯定是非IPv4格式 
                        result = null;
                    else
                    {
                        if (result.IndexOf(",") != -1)
                        {
                            //有“,”,估计多个代理。取第一个不是内网的IP。 
                            result = result.Replace(" ", "").Replace("'", "");
                            string[] temparyip = result.Split(",;".ToCharArray());
                            for (int i = 0; i < temparyip.Length; i++)
                            {
                                if (IsIPAddress(temparyip[i])
                                    && temparyip[i].Substring(0, 3) != "10."
                                    && temparyip[i].Substring(0, 7) != "192.168"
                                    && temparyip[i].Substring(0, 7) != "172.16.")
                                {
                                    return temparyip[i];    //找到不是内网的地址 
                                }
                            }
                        }
                        else if (IsIPAddress(result)) //代理即是IP格式 
                            return result;
                        else
                            result = null;    //代理中的内容 非IP,取IP 
                    }

                }

                string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null
                    && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty)
                    ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
                    : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                if (null == result || result == String.Empty)
                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                if (result == null || result == String.Empty)
                    result = HttpContext.Current.Request.UserHostAddress;

                return result;
            }
        }
        /// <summary>
        /// 判断是否是IP地址格式 0.0.0.0
        /// </summary>
        /// <param name="str1">待判断的IP地址</param>
        /// <returns>true or false</returns>
        public static bool IsIPAddress(string str1)
        {
            if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15)
                return false;

            string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";

            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
            return regex.IsMatch(str1);
        }

#20


 问题被人遗忘了,自己顶一下!

#21


已经解决,是ISA防火墙设置问题。
http://www.cnblogs.com/cnaspnet/archive/2008/07/05/1236181.html

#22


楼主,我也碰到一样的问题,可是我对ISA的设置不太熟悉,能否将ISA的设置列详细点,以供大家参考,谢谢!

#23


引用 6 楼 only_endure 的回复:
Request.ServerVariables("Url") 
返回服务器地址

Request.ServerVariables("Path_Info") 
客户端提供的路径信息

Request.ServerVariables("Appl_Physical_Path") 
与应用程序元数据库路径相应的物理路径

Request.ServerVariables("Path_Tra……
不错

#24


我现在遇到了同样的问题,但是我没有安装isa防火墙啊