简体   繁体   中英

IPv6 reader in Python

I have a small Python code to read the IP address of the client visiting my Flask website, hosted on pythonanywhere.com:

from flask import Flask, request 

app = Flask(__name__)

@app.route('/')
def hello_world():
    ipread1 = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
    print("The client IP1 is: %s" % (ipread1))
    return 'Hello  World!'

if __name__ == '__main__':
    app.run()

This correctly returns my IPv4 address in the server log each time I refresh the webpage. However, I would like it to instead give out my IPv6 address (which I've already checked that I do have).

To do this, I have tried changing:

app.run() to app.run(host='::')

But this still just gives my IPv4 address. How can I force Python to give my IPv6 address?

Consider the first case with app.run() . What you get is a IPV4 address of the client such as:

The client IP1 is: 127.0.0.1

Now, if You add the argument host app.run(host='::') you listen on the IPv6 socket and get something like:

The client IP1 is: ::ffff:127.0.0.1

Is the client using IPv6?
No, the client is still using its IPv4 address and talking with an IPv4 server. So, no diffference from its point of view. What changes is that you get v4-mapped-on-v6 address with the following form:

000 ... 000 |   FFFF  | IPv4 Address
   80 bits    16 bits     32 bits   

See for example the corresponding RFC .

In such a way, from the point of view of the server it will look like it comes from an IPv6 host and it would be able to use a dual-stack IPv4/IPv6.

If you want to see something different, you have to change the way your client send its requests.

PythonAnywhere处理的所有请求都通过IPv4来处理,因此您不会看到IPv6地址。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM