[英]How to get client IP address using python bottle framework
I need client IP address using python.我需要使用 python 的客户端 IP 地址。 I have tried below code but its not working in server:
我试过下面的代码,但它在服务器上不起作用:
from socket import gethostname, gethostbyname
ip = gethostbyname(gethostname())
print ip
On the server, I get '127.0.0.1' every time.在服务器上,我每次都得到“127.0.0.1”。 Is there any way to find IP address of the client?
有没有办法找到客户端的IP地址?
You're getting the IP address of your server , not of your server's clients .您正在获取服务器的 IP 地址,而不是服务器客户端的 IP 地址。
You want to look at the request's REMOTE_ADDR
, like this:您想查看请求的
REMOTE_ADDR
,如下所示:
from bottle import Bottle, request
app = Bottle()
@app.route('/hello')
def hello():
client_ip = request.environ.get('REMOTE_ADDR')
return ['Your IP is: {}\n'.format(client_ip)]
app.run(host='0.0.0.0', port=8080)
EDIT #1 : Some folks have observed that, for them, the value of REMOTE_ADDR
is always the same IP address (usually 127.0.0.1
).编辑 #1 :有些人观察到,对他们来说,
REMOTE_ADDR
的值总是相同的 IP 地址(通常是127.0.0.1
)。 This is because they're behind a proxy (or load balancer).这是因为它们位于代理(或负载平衡器)后面。 In this case, the client's original IP address is typically stored in header
HTTP_X_FORWARDED_FOR
.在这种情况下,客户端的原始 IP 地址通常存储在标头
HTTP_X_FORWARDED_FOR
。 The following code will work in either case:以下代码适用于任何一种情况:
@app.route('/hello')
def hello():
client_ip = request.environ.get('HTTP_X_FORWARDED_FOR') or request.environ.get('REMOTE_ADDR')
return ['Your IP is: {}\n'.format(client_ip)]
EDIT #2 : Thanks to @ArtOfWarfare's comment, I learned that REMOTE_ADDR
is not required per PEP-333.编辑#2 :感谢@ArtOfWarfare 的评论,我了解到每个 PEP-333 不需要
REMOTE_ADDR
。 Couple of observations:几个观察:
The REMOTE_ADDR variable MUST be set to the network address of the client sending the request to the server.
REMOTE_ADDR 变量必须设置为客户端向服务器发送请求的网络地址。
HTTP_REMOTE_ADDR
, only going as far as this (emphasis mine):HTTP_REMOTE_ADDR
,只是这样(强调我的):A server or gateway SHOULD attempt to provide as many other CGI variables as are applicable.
服务器或网关应该尝试提供尽可能多的其他适用的 CGI 变量。
HTTP_REMOTE_ADDR
.HTTP_REMOTE_ADDR
。 AFAICT, it's a de facto "standard." Server might be behind a proxy.服务器可能位于代理后面。 Use this for proxy and forward support:
将此用于代理和转发支持:
request.environ.get('HTTP_X_FORWARDED_FOR') or request.environ.get('REMOTE_ADDR')
If you're trying to get the external IP, you will need to get it from an external source, ie whatismyip.com or somewhere that offers an api.如果您尝试获取外部 IP,则需要从外部来源获取它,即 whatismyip.com 或提供 api 的某个地方。 If that's what you're looking for, take a look at the Requests module http://docs.python-requests.org/
如果这就是您要查找的内容,请查看请求模块http://docs.python-requests.org/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.