0

I'd like to know how to get the IP of the user connected to my application ( asp.net mvc4) . I tried:

IPHostEntry ipHostEntry = Dns.GetHostByName(Dns.GetHostName());
IPAddress ipAddress = ipHostEntry.AddressList[0];

But it didn't work.

So how can I modify the snippet to get the Ip` or the connected user?

4b0
  • 21,981
  • 30
  • 95
  • 142
Lamloumi Afif
  • 8,941
  • 26
  • 98
  • 191
  • Is this similar to what you're looking for? http://stackoverflow.com/questions/735350/how-to-get-a-users-client-ip-address-in-asp-net – JayH Jun 28 '13 at 08:59

1 Answers1

1

Here's the converted C# code from the similar question @jamieHennerley suggested.

protected string GetIPAddress()
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;

            string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (!string.IsNullOrEmpty(ipAddress))
            {
                string[] addresses = ipAddress.Split(',');
                if (addresses.Length != 0)
                {
                    return addresses[0];
                }
            }

            return context.Request.ServerVariables["REMOTE_ADDR"];
        }
vendettamit
  • 14,315
  • 2
  • 32
  • 54
  • the result is always `::1` why? – Lamloumi Afif Jun 28 '13 at 09:12
  • ::1 is an IPv6 address and an abbreviation for 0:0:0:0:0:0:0:1 that is the loopback address to the local machine. So ::1 is the same as 127.0.0.1 only via IPv6 instead of IPv4. You might be having IPV6 installed on you machine. Once the application is deployed it should work fine and display the IPv4 address instead. – vendettamit Jun 28 '13 at 09:18