4

I have an ASP.Net 4.0 application, published on a company intranet network on an IIS 7.0 server, and I want to save the client's IP address in my database. So I want to get client's IP address and computer name.

I tried methods from internet searches but I get "SERVER IP" an "SERVER NAME". I think it's logical because all methods I tried is C# code that proceed server side.

So, I think I must use client side code like JavaScript.

Does anyone have the right method to do this?

pimvdb
  • 151,816
  • 78
  • 307
  • 352
SaBeR
  • 41
  • 1
  • 1
  • 3

1 Answers1

13

You could use the UserHostAddress and UserHostName properties on the Request object:

string ip = Request.UserHostAddress;
string hostname = Request.UserHostName;
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • That may be the best bet, but I know my browsers never send those headers. Maybe those are an IE feature. – Pointy Sep 18 '11 at 14:47
  • 2
    @Pointy, the user ip address is not sent as any header. It is determined from the underlying socket so it doesn't really matter which browser was used to send the HTTP request. As a matter of fact you could write a .NET program using a WebClient to send the HTTP request from some machine and the IP address of the client will still be fetched. As far as the user hostname, ASP.NET tries to use DNS to resolve it. – Darin Dimitrov Sep 18 '11 at 14:48
  • 1
    Ah I see what you mean - it's a function of the server-side infrastructure. Thanks! – Pointy Sep 18 '11 at 14:50
  • 3
    You should note that this will breakdown if there is a proxy or load balancer in the mix. ASP.NET will get the IP address of the proxy or the load balancer rather than the client IP address, there is a standard that if implemented by the intermediate devices can help, they will add the X-Forwarded-For header. – Chris Taylor Sep 18 '11 at 15:27
  • `Request.UserHostAddress` works for IP address but `Request.UserHostName` returns the same thing: in my case, testing locally returned `::1` for both (while testing remotely for `Request.UserHostAddress` did work). I ended up using `Dns.GetHostEntry(Request.ServerVariables["REMOTE_ADDR"]).HostName;`, which worked to get the hostname. – TylerH Sep 03 '20 at 14:59