python获取客户端ip地址_如何使用python bottle框架获取客户端IP地址

I need client IP address using python. 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. Is there any way to find IP address of the client?

解决方案

You're getting the IP address of your server, not of your server's clients.

You want to look at the request's REMOTE_ADDR, like this:

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). 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. 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. Couple of observations:

The CGI spec does require REMOTE_ADDR:

The REMOTE_ADDR variable MUST be set to the network address of the client sending the request to the server.

However, PEP-333 does not explicitly require HTTP_REMOTE_ADDR, only going as far as this (emphasis mine):

A server or gateway SHOULD attempt to provide as many other CGI variables as are applicable.

All of the (admittedly few) web frameworks that I'm familiar with set HTTP_REMOTE_ADDR. AFAICT, it's a de facto "standard." But technically, YMMV.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值