0

I want to get the client ip when the user submit a form in my site. I try to use that command: Request.UserHostAddress

but I get instead of the ip: ::1

What should I do?

Thank you!

user2097810
  • 735
  • 6
  • 17
  • 25

4 Answers4

5

That's because you're testing locally. ::1 is the IPv6 equivalent to 127.0.0.1.

What is IP address '::1'?

Community
  • 1
  • 1
David East
  • 31,526
  • 6
  • 67
  • 82
2

::1 is the same as localhost

in ASP.NET you can do this to get the user IP Address

public static string GetUserIpAddress()
{
    string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (string.IsNullOrEmpty(ip))
    {
        ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        if (ip == "::1") ip = "127.0.0.1"; // localhost
    }
    return ip;
}
balexandre
  • 73,608
  • 45
  • 233
  • 342
2

You can use REMOTE_ADDR, but it might not work if you are accessing the site locally, it will show local host. Below code will help you

        string clientIp = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
     if( !string.IsNullOrEmpty(clientIp) ) 
{
      string[] forwardedIps = clientIp.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries );
      clientIp = forwardedIps[forwardedIps.Length - 1];
     } 
else {
      clientIp = context.Request.ServerVariables["REMOTE_ADDR"];
     }
Zerotoinfinity
  • 6,290
  • 32
  • 130
  • 206
1

::1 is a IPv6 loopback address.That means 127.0.0.1

Ipv4  127.0.0.1    localhost
Ipv6  ::1          localhost

localhost

Nagaraj S
  • 13,316
  • 6
  • 32
  • 53