Capture IP Address of Client Machine

For one of my recent user story, I had to find the IP address of the client machine. Nothing to worry about here. I just used the following property as suggested by several posts that I googled.

<br />string clientIp = HttpContext.Current.Request.UserHostAddress;<br />

The user story was completed and accepted. Everyone forgot about it.

But then after a couple of weeks, we got a defect story that says the IP address returned is not that of the client machine, but that of the load balancer. I was like WHAT???

Then, after a couple of hours of diving into the details, I found out what was the causing this issue. It turns out that the issue was with the property HttpRequest.UserHostAddress. We had used this property to get the IP host address of the remote client machine, which simply returns the server variable REMOTE_ADDR. This server variable returns the IP address of the remote host making the request. If there is a proxy server or a load balancer in the middle, this property returns the IP address address of that machine, and not that of the client machine.

So, to resolve this issue, we used another server variable HTTP_X_FORWARDED_FOR. For cases where load balancer or proxy machines are used, this variable contains the correct IP address.

The resulting code looked like this:

</p><p>string clientIp = String.Empty;</p><p>&lt;br/&gt;if(Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)</p><p>{</p><p>     clientIp = Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];</p><p>}</p><p>else</p><p>{</p><p>      clientIp = Current.Request.UserHostAddress;</p><p>}</p><p>

Thus, the defect story was closed!! Yay!!

Lesson learnt for me: Need to dive into details for any built-in property or functions that I use from today onwards!! 🙂

Happy Coding!!!:)

Leave a comment