We have Request.UserHostAddress
to get the IP address in ASP.NET, but this is usually the user's ISP's IP address, not exactly the user's machine IP address who for example clicked a link. How can I get the real IP Address?
For example, in a Stack Overflow user profile it is: "Last account activity: 4 hours ago from 86.123.127.8", but my machine IP address is a bit different. How does Stack Overflow get this address?
In some web systems there is an IP address check for some purposes. For example, with a certain IP address, for every 24 hours can the user just have only 5 clicks on download links? This IP address should be unique, not for an ISP that has a huge range of clients or Internet users.
Did I understand well?
UPDATE: Thanks to Bruno Lopes. If several ip addresses could come then need to use this method:
All of the responses so far take into account the non-standardized, but very common,
X-Forwarded-For
header. There is a standardizedForwarded
header which is a little more difficult to parse out. Some examples are as follows:I have written a class that takes both of these headers into account when determining a client's IP address.
Below are some unit tests that I used to validate my solution:
If you are using CloudFlare, you can try this Extension Method:
then
Combining the answers from @Tony and @mangokun, I have created the following extension method:
I think I should share my experience with you all. Well I see in some situations REMOTE_ADDR will NOT get you what you are looking for. For instance, if you have a Load Balancer behind the scene and if you are trying to get the Client's IP then you will be in trouble. I checked it with my IP masking software plus I also checked with my colleagues being in different continents. So here is my solution.
When I want to know the IP of a client, I try to pick every possible evidence so I could determine if they are unique:
Here I found another sever-var that could help you all if you want to get exact IP of the client side. so I am using : HTTP_X_CLUSTER_CLIENT_IP
HTTP_X_CLUSTER_CLIENT_IP always gets you the exact IP of the client. In any case if its not giving you the value, you should then look for HTTP_X_FORWARDED_FOR as it is the second best candidate to get you the client IP and then the REMOTE_ADDR var which may or may not return you the IP but to me having all these three is what I find the best thing to monitor them.
I hope this helps some guys.