Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get client IP address using python bottle framework

Tags:

python

bottle

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?

like image 211
user3414814 Avatar asked Jul 14 '15 11:07

user3414814


3 Answers

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.
like image 101
ron rothman Avatar answered Nov 14 '22 17:11

ron rothman


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')
like image 25
Farshid Ashouri Avatar answered Nov 14 '22 16:11

Farshid Ashouri


If you're trying to get the external IP, you will need to get it from an external source, i.e whatismyip.com or somewhere that offers an api. If that's what you're looking for, take a look at the Requests module http://docs.python-requests.org/

like image 2
blasko Avatar answered Nov 14 '22 17:11

blasko