Home > Blockchain >  How to get client ip address in MVC
How to get client ip address in MVC

Time:03-03

I would like to pull out the client's PC's IP address. I have tried below approaches but it always returns "::1"

1. var test = this.Request.ServerVariables.Get("REMOTE_ADDR");

2. request.UserHostAddress;

Any inputs?

CodePudding user response:

You can get the I.P address like this in your Controller method:

If the client machine is behind a proxy server, we can check for the variable HTTP_X_FORWARDED_FOR:

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

If the IP Address is not found in the HTTP_X_FORWARDED_FOR server variable, it means that it is not using any Proxy Server and hence the IP Address is now checked in the REMOTE_ADDR server variable.

Note: On your local machine, the I.P address will be shown as ::1 which is an IPV6 loopback address (i.e. localhost). An IPV4 address would be 127.0.0.1.

This is because in such case the Client and Server both are the same machine. When the application is deployed on the server, then the result will be different.

CodePudding user response:

The below code should give you collection of client IP Addresses. If not, please post your code snippet so we can verify:

public static System.Collections.Generic.IReadOnlyCollection<System.Net.IPAddress> GetIpAddresses()
{
    var ipAddresses = new List<System.Net.IPAddress>();

    foreach (var values in GetValues(System.Web.HttpContext.Current.Request.Headers, "X-Forwarded-For"))
    {
        foreach (var ipv in values.Split(new char[] { ',', ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
        {
            if (ipv.Contains(":"))
            {
                var array = ipv.Split(':');
                ipAddresses.Add(array.Length == 2 ? System.Net.IPAddress.Parse(array[0].Trim()) : System.Net.IPAddress.Parse(ipv.Trim()));
            }
            else
            {
                ipAddresses.Add(System.Net.IPAddress.Parse(ipv));
            }
        }
    }

    if (request.UserHostAddress != null)
    {
        if (request.UserHostAddress.Contains(":"))
        {
            var array = request.UserHostAddress.Split(':');
            ipAddresses.Add(array.Length == 2 ? System.Net.IPAddress.Parse(array[0].Trim()) : System.Net.IPAddress.Parse(request.UserHostAddress.Trim()));
        }
        else
        {
            ipAddresses.Add(System.Net.IPAddress.Parse(request.UserHostAddress));
        }
    }
    return ipAddresses;
}
  • Related