在c#中获取用户IP

我想获取用户IP并将其插入表中。我正在使用以下内容:

SqlCommand cmd = new SqlCommand("INSERT INTO Raspunsuri Values(@raspuns,@cnp,@data,'1',@ip)", con); cmd.Parameters.AddWithValue("@cnp", Session["sesiune_cnp"]); cmd.Parameters.AddWithValue("@raspuns", textbox1.Text); cmd.Parameters.AddWithValue("@data", DateTime.Now.ToLocalTime()); cmd.Parameters.AddWithValue("@ip", HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]); 

但是当我看到Ip栏中的表格时,我只得到1 …你能给我一个解释吗?

你可以使用:

 string ipAddress = Request.UserHostAddress; 

您的程序可能正常运行。 :: 1是IPv6中的本地IP地址。 如果您在Windows Vista或更高版本上从本地计算机上运行此操作,则一切正常。

这是获取用户IP地址的更好方法:

 string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (string.IsNullOrEmpty(ip)) { ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } 

如果用户位于某种类型的代理后面,那么您将获得代理地址而不是最终用户的IP地址。 HTTP_X_FORWARDED_FOR通常是用户的真实IP地址。 如果那是空的那么你应该在REMOTE_ADDR