1

How do I get the remote IP address in Python?

I tried searching Google but couldn't find any useful results. os.environ['REMOTE_ADDR'] is giving KeyError: 'REMOTE_ADDR'

Adam
  • 2,948
  • 10
  • 43
  • 74

2 Answers2

3

You're accessing the operating system's os environment, not the request's.

The WSGI callable should be passed two variables, environ and start_response, and that environ variable will have the variables you're looking for.

Those variables would only be present in the actual os.environ if you were running a CGI app.


Depending on the web framework you're using, you might not have access to this. If you're passed a request object, this will likely end up in request.META or something similar.

If you're not using any framework, that will be in the environ dict that is passed to your wsgi callable.

As noted in another answer, REMOTE_ADDR doesn't have to be their as per the spec, but if you're using Apache's mod_wsgi, it should be there.

Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116
  • Also worth mentioning, `REMOTE_ADDR` may be the address of a forwarder if your setup has any web application firewall, a proxy that is handling the requests (like nginx) or other such setup. In this case, its also worth checking for the presence of `HTTP_X_FORWARDED_FOR` – Burhan Khalid Jun 02 '13 at 04:21
2

If you have access to the TCP socket, you can use socket.getpeername() to get the remote address. Docs are here.

Graeme Perrow
  • 56,086
  • 21
  • 82
  • 121