简体   繁体   中英

How can I get a user's IP address in C#/asp.net/MVC 5?

The following code works OK locally, but it will only get the server's IP (if I'm correct).

try
{
    string externalIP;
    externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
    externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                 .Matches(externalIP)[0].ToString();
    model.IpCreacion = externalIP;
}
catch { }

I can't test this right now, because the two guys at my office that can make this as a public URL for testing on a server aren't here today. The code is in the controller of the project, so it runs on the server every time a client executes the app, it's not actually the client who is getting the IP address.

How can I make the client get his IP address, instead of the server, executing the code I just showed?

If I managed to put this functionality in a view, would it work as I'm intending to?

UPDATE: I tried other methods posted as answers, like

string ip = System.Web.HttpContext.Current.Request.UserHostAddress;

and

model.IpCreacion = null;
model.IpCreacion = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

if (string.IsNullOrEmpty(model.IpCreacion))
{
    model.IpCreacion = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}

but now I'm only getting ::1 as a result. Which didn't happen before, as I was getting a correct IP address.

That gets only IP of server, because you send the request from Web Server to checkip.dyndns.org.

To get the client IP, you need to use JavaScript and do the same thing.

$.get('http://checkip.dyndns.org/', function(data) {
    console.log(data); // client IP here.
})

UPDATED:

If you need client IP Address in ASP.NET Core, you can inject this service

private IHttpContextAccessor _accessor;

And use it as

_accessor.HttpContext.Connection.RemoteIpAddress.ToString()

Or in ASP.NET Framework

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

如果您想获取客户端 IP 地址,请访问 stackoverflow 中的以下帖子如何在 ASP.NET MVC 中获取客户端的 IP 地址?

Public string GetIp()  
{  
    string ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];  
    if (string.IsNullOrEmpty(ip))  
    {  
       ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];  
    }  
    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