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'
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'
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.
If you have access to the TCP socket, you can use socket.getpeername()
to get the remote address. Docs are here.