简体   繁体   English

Python中的IPv6阅读器

[英]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: 我有一个小的Python代码来读取访问我在Flask网站上托管的Flask网站的客户端的IP地址:

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. 每次刷新网页时,这都会在服务器日志中正确返回我的IPv4地址。 However, I would like it to instead give out my IPv6 address (which I've already checked that I do have). 但是,我希望它给出我的IPv6地址(我已经检查过我的确有)。

To do this, I have tried changing: 为此,我尝试更改:

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

But this still just gives my IPv4 address. 但这仍然只是我的IPv4地址。 How can I force Python to give my IPv6 address? 如何强制Python提供我的IPv6地址?

Consider the first case with app.run() . 考虑用app.run()的第一种情况。 What you get is a IPV4 address of the client such as: 您得到的是客户端的IPV4地址,例如:

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: 现在,如果您添加参数host app.run(host='::')您将在IPv6套接字上侦听并得到类似以下内容:

The client IP1 is: ::ffff:127.0.0.1

Is the client using IPv6? 客户端使用IPv6吗?
No, the client is still using its IPv4 address and talking with an IPv4 server. 否,客户端仍在使用其IPv4地址并与IPv4服务器通信。 So, no diffference from its point of view. 因此,从它的角度看,没有区别。 What changes is that you get v4-mapped-on-v6 address with the following form: 所发生的变化是,您使用以下格式获取了v4-mapped-on-v6 address

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

See for example the corresponding RFC . 例如,参见相应的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. 这样,从服务器的角度来看,它看起来像是来自IPv6主机,并且将能够使用双栈IPv4 / IPv6。

If you want to see something different, you have to change the way your client send its requests. 如果您希望看到不同的内容,则必须更改客户端发送请求的方式。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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