Anyname Donotcare
Anyname Donotcare

Reputation: 11393

The difference among four ways to get the client ip address

Q:

I need to know the difference among the following:

Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ;


Request.ServerVariables["REMOTE_ADDR"];

System.Web.HttpContext.Current.Request.UserHostAddress;

System.Net.IPAddress[] strClientIPAddress = System.Net.Dns.GetHostAddresses(Environment.MachineName);

I want to get the client IP address (the user who access the site)and I'm confused among the previous methods which one more accurate.

Upvotes: 1

Views: 2211

Answers (1)

Waqas Raja
Waqas Raja

Reputation: 10872

I always use the third option to get the client (or user) ip address.

System.Web.HttpContext.Current.Request.UserHostAddress;

The first two methods also do the same thing.

But the last method do not return the client ip, it will return the server ip where your site is hosted. And for calling this method you must need to specify host name or ip address. However, Environment.MachineName returns the server name and therefore it will return server's ip not the user's ip.

For more information about your first two option I find the difference by googling, here it is

Upvotes: 6

Related Questions