2

I created a flask API. Whoever visits that API, I am able to track their IP address. In my situation, i am able to track the local ip from any system which is connected to my internet where I ran the code locally. I deployed the code when I ran the API. It is able to track the public address. I want both public and local IP addresses to be tracked after deployment.

Is there any way to track the local address along with the public address even after deployment using flask and python?

 from netifaces import interfaces, ifaddresses, AF_INET
 for ifaceName in interfaces():
       addresses = [i['addr'] for i in 
       ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )]
       print '%s: %s' % (ifaceName, ', '.join(addresses))

 import socket    
 hostname = socket.gethostname()    
 IPAddr = socket.gethostbyname(hostname)   

i tried all this but of no use not able to get my desired output

@app.route("/get_my_ip", methods=["GET"])
def get_my_ip():
      return jsonify({'ip': request.environ['REMOTE_ADDR']}), 200

Result:10.0.0.1

After the code deployment I am able to get only the public IP. I need to track the local IP along with the public IP.

For example: if 10 different systems connected to one internet used the deployed api, I should get 10 different IP addresses but i am getting the public IP which is common to all. But I expect both public IP and local UP like 106.89.78.90(public IP) 10.0.0.1(private IP) from one system, then 106.89.78.90/10.0.0.2 from another system, and so on.

aschultz
  • 1,658
  • 3
  • 20
  • 30
Swarnitha
  • 45
  • 7
  • 1
    do you know how NAT works? – njzk2 Jul 01 '19 at 06:06
  • A client will connect from exactly one IP address. In IPv4 this can be an address from a private range if both the server and the client are in this range. If not and in some other cases the server will see a public IP. Then the private IP has been replaced in the packets by a router and can not be seen by the server. The situation might be different if a proxy server is involved. – Klaus D. Jul 01 '19 at 08:21

1 Answers1

0

You need to set up your server (nginx/apache/caddy etc) so that it adds a special header X-Forwarded-For with actual IPs to every request.

Related: Get IP address of visitors using Flask for Python

abdusco
  • 9,700
  • 2
  • 27
  • 44
  • from flask import request request.environ.get('HTTP_X_REAL_IP', request.remote_addr) should i use this in code instead of {'ip': request.environ['REMOTE_ADDR']} in server where i deploy – Swarnitha Jul 01 '19 at 06:15
  • More like `from werkzeug.contrib.fixers import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app)` then `request.remote_addr` – abdusco Jul 01 '19 at 06:17
  • i am not getting the desired output ,i am deploying my code in apache server – Swarnitha Jul 01 '19 at 12:13
  • Try adding `RemoteIPHeader X-Forwarded-For` in your `.htaccess` file – abdusco Jul 01 '19 at 12:20