简体   繁体   中英

C# IP Address always ::1

I've tried something explained below, somehow, IP Address is always ::1, on both local and server side,

Here are the codes, I tried;

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);

Is there anyone to know why and how to solve it ?

Thanks in Advance!

The code bellow works for me.

When I run the app in localhost I always get ::1. But, it works greate on server side. The app is running in 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM