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'

6
  • 2
    @AshwiniChaudhary: that's wrong. He wants the IP address of a client connecting to his web app, not of the server on which his app is running. Commented Jun 2, 2013 at 2:09
  • What does your stack look like? Commented Jun 2, 2013 at 2:11
  • @ThomasOrozco Debian, Apache 2.2 and Python 2.7 Commented Jun 2, 2013 at 2:18
  • @Cairnarvon you're right, but can't remove the close vote now. Commented Jun 2, 2013 at 2:23
  • @AdamSilver mod_wsgi? Commented Jun 2, 2013 at 2:24

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.