如何在 Python 中获取远程 IP 地址?
我尝试搜索谷歌,但找不到任何有用的结果。os.environ['REMOTE_ADDR']
正在给KeyError: 'REMOTE_ADDR'
如何在 Python 中获取远程 IP 地址?
我尝试搜索谷歌,但找不到任何有用的结果。os.environ['REMOTE_ADDR']
正在给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.
如果您可以访问 TCP 套接字,则可以使用它socket.getpeername()
来获取远程地址。文档在这里。