Search code examples
asp.netip-addresswebrequest

Do all web requests contain the requestor's IP?


Am I able to depend on a requestor's IP coming through on all web requests?

I have an asp.net application and I'd like to use the IP to identify unauthenticated visitors. I don't really care if the IP is unique as long as there is something there so that I don't get an empty value.

If not I guess I would have to handle the case where the value is empty.

Or is there a better identifier than IP?


Solution

  • You can get this from Request.ServerVariables["REMOTE_ADDR"].

    It doesn't hurt to be defensive. If you're worried about some horrible error condition where this isn't set, check for that case and deal with it accordingly.

    There could be many reasons for this value not to be useful. You may only get the address of the last hop, like a load balancer or SSL decoder on the local network. It might be an ISP proxy, or some company NAT firewall.

    On that note, some proxies may provide the IP for which they're forwarding traffic in an additional HTTP header, accessible via Request.ServerVariables["HTTP_X_FORWARDED_FOR"]. You might want to check this first, then fall back to Request.ServerVariables["REMOTE_ADDR"] or Request.UserHostAddress.

    It's certainly not a bad idea to log these things for reference/auditing.