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:
REMOTE_ADDR
:The REMOTE_ADDR variable MUST be set to the network address of the client sending the request to the server.
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.
HTTP_REMOTE_ADDR
. AFAICT, it's a de facto "standard." But technically, YMMV.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, 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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With