How to get client IP address using python flash memory

I need the client IP address using python. I tried the code below but did not work on the 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 the client IP address?

+5
source share
3 answers

You get the IP address of your server, not the clients of your server.

You want to see the REMOTE_ADDR request, for example:

 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: Some people have noticed that for them, the value of REMOTE_ADDR is always the same IP address (usually 127.0.0.1 ). This is because they are behind the proxy (or load balancing). In this case, the source IP address of the client is usually stored in the HTTP_X_FORWARDED_FOR header. The following code will work anyway:

 @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)] 
+5
source

The server may be located behind the proxy server. Use this for proxy support and direct support:

 request.environ.get('HTTP_X_FORWARDED_FOR') or request.environ.get('REMOTE_ADDR') 
+5
source

If you are trying to get an external IP address, you will need to get it from an external source, i.e. whatismyip.com or somewhere offering an api. If this is what you are looking for, check out the Requests module http://docs.python-requests.org/

+2
source

All Articles