我已经尝试了下面解释的内容,不知何故,IP地址始终是:: 1,在本地和服务器端,
以下是我试过的代码;
m_CallerIP = string.IsNullOrEmpty(req.ServerVariables["HTTP_CLIENT_IP"]) ? req.UserHostAddress : req.ServerVariables["HTTP_CLIENT_IP"];
string Port = string.IsNullOrEmpty(req.ServerVariables["HTTP_CLIENTPORT"]) ? req["HTTP_CLIENTPORT"] : req.ServerVariables["CLIENTPORT"];
string asd2 = String.IsNullOrEmpty(req.ServerVariables["REMOTE_ADDR"]) ? req.UserHostAddress : req.ServerVariables["REMOTE_ADDR"];
string asd23 = String.IsNullOrEmpty(req.ServerVariables["HTTP_X_FORWARDED_FOR"]) ? req.UserHostAddress : req.ServerVariables["HTTP_X_FORWARDED_FOR"];
string asd4 = req.UserHostAddress;
IPAddress address = IPAddress.Parse(m_CallerIP);
IPAddress address1 = IPAddress.Parse(asd2);
IPAddress address2 = IPAddress.Parse(asd23);
IPAddress address3 = IPAddress.Parse(asd4);
有没有人知道为什么以及如何解决它?
提前致谢!
答案 0 :(得分:0)
下面的代码对我有用。
当我在localhost中运行应用程序时,我总是得到:: 1。但是,它在服务器端很有用。该应用程序在Azure中运行。
string ip = "";
ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ip))
ip = ip.Split(',').Last().Trim();
else
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (ip == "::1")
ip = "";
if (ip.IndexOf(':') > 0)
ip = ip.Substring(0, ip.IndexOf(':'));
return ip;