How can I get the client's IP address in ASP.NET MVC?
Asked 07 September, 2021
Viewed 2K times
  • 62
Votes

I'm totally new to the ASP.NET MVC stack, and I was wondering what happened to the simple Page object and the Request ServerVariables object?

Basically, I want to to pull out the client PC's IP address, but I fail to understand how the current MVC structure has changed all of this.

As far as I can understand, most of the variable objects has been replaced by the HttpRequest variants.

Anybody care to share some resources? There is really a sea of stuff to learn in the ASP.NET MVC world. :)

For example, I have a static class with this current function. How do I get the same result using ASP.NET MVC?

public static int getCountry(Page page)
{
    return getCountryFromIP(getIPAddress(page));
}

public static string getIPAddress(Page page)
{
    string szRemoteAddr = page.Request.ServerVariables["REMOTE_ADDR"];
    string szXForwardedFor = page.Request.ServerVariables["X_FORWARDED_FOR"];
    string szIP = "";

    if (szXForwardedFor == null)
    {
        szIP = szRemoteAddr;
    }
    else
    {
        szIP = szXForwardedFor;

        if (szIP.IndexOf(",") > 0)
        {
            string [] arIPs = szIP.Split(',');

            foreach (string item in arIPs)
            {
                if (!isPrivateIP(item))
                {
                    return item;
                }
            }
        }
    }
    return szIP;
}

And how do I call this function from the controller page?

6 Answer