2

I am trying to get the IP address of the user who is browsing the website, might be through mobile phones or PC. I have tried using a set of code, but what I get back is ::1, may I know if this is wrong or it's meant to be like that?

private string GetUser_IP()
{
    string VisitorsIPAddr = string.Empty;
    if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
    {
        VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    }
    else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
    {
        VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
    }
    ipAddress = VisitorsIPAddr;    
    return ipAddress;
}

Thank you for the help in advance.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Arane
  • 323
  • 4
  • 19
  • `::1` is ipv6 localhost, i.e its you - this is expected when you access the site locally. – Alex K. Jul 11 '18 at 10:41
  • @AlexK. so would it be safe to say that if it's not accessed locally, the web will be able to obtain the user's IP? – Arane Jul 11 '18 at 10:43
  • `::1` is the ipv6 equivalent to `127.0.0.1`, it means it is your own machine – Cleptus Jul 11 '18 at 10:44
  • I would go https://msdn.microsoft.com/en-us/library/system.web.httprequest.userhostaddress(v=vs.110).aspx because not all clients are behind a load balancer – Cleptus Jul 11 '18 at 10:46
  • 1
    Yes, see this: [How to get a user's client IP address in ASP.NET?](https://stackoverflow.com/questions/735350/how-to-get-a-users-client-ip-address-in-asp-net) - note that forwarded-for can contain multiple addresses. – Alex K. Jul 11 '18 at 10:47

1 Answers1

2

::1 and 127.0.0.1 and localhost are same, they means THIS computer. You are connected to your application on same machine, where you have an application. Try to deploy application to some server.

Remember to make sure if you are getting a public or private IP address.

Maciej Pulikowski
  • 2,457
  • 3
  • 15
  • 34