使用localhost作为地址执行网络请求时会有2s的延时,这个问题在Linux并不存在,本文分析并提出解决方案。
问题复现
主要体现在windows 下,python 使用 flask 将 localhost 作为地址时有2s延迟
原因分析
问题在于解析localhost时,优先按照ipv6地址解析,这个可以通过ping命令验证:
12345C:\Users\Admin>ping localhost正在 Ping VVD [::1] 具有 32 字节的数据:来自 ::1 的回复: 时间<1ms来自 ::1 的回复: 时间<1ms
解决方案
关闭ipv6的方案尝试过几次,都没有效果
修改host文件添加 127.0.0.1 localhost 也没有用
问题症结在于ipv6和ipv4的优先级,如果ipv4的更高,则会优先使用ipv4地址
查看优先级
命令:netsh interface ipv6 show prefixpolicies
1234567891011121314C:\WINDOWS\system32>netsh interface ipv6 show prefixpolicies查询活动状态...优先顺序 标签 前缀---------- ----- -------------------------------- 50 0 ::1/128 40 1 ::/0 35 4 ::ffff:0:0/96 30 2 2002::/16 5 5 2001::/32 3 13 fc00::/7 1 11 fec0::/10 1 12 3ffe::/16 1 3 ::/96
其中::1/128和::/0是ipv6的地址,::/96是ipv4
我们需要将ipv4地址前移到最高优先级
修改优先级
1234netsh int ipv6 set prefix ::/96 50 0netsh int ipv6 set prefix ::ffff:0:0/96 40 1netsh int ipv6 set prefix ::1/128 10 4netsh int ipv6 set prefix ::/0 5 5
此时优先级关系位:
1234567891011121314C:\Users\Admin>netsh interface ipv6 show prefixpolicies查询活动状态...优先顺序 标签 前缀---------- ----- -------------------------------- 50 0 ::/96 40 1 ::ffff:0:0/96 30 2 2002::/16 10 4 ::1/128 5 5 2001::/32 5 5 ::/0 3 13 fc00::/7 1 12 3ffe::/16 1 11 fec0::/10
问题解决
测试
12345C:\Users\Admin>ping localhost正在 Ping VVD [127.0.0.1] 具有 32 字节的数据:来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=64来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=64
而且使用localhost做地址执行各种任务都快了很多
参考资料
http://cache.baiducontent.com/c?m=7nuW37g3ClnQQ4TESYoMV19XOKkNHhXUETAL5Gd1cAHho68Clboy-NpJhHQwM7-KzLJm3K6xlH7bkQPB168FqRbbiTQ_BBXAt5gnV_T5WcCviPr-g7bk_9TCft1XFmmNZAt-uKNslVspTU6xdNnnmMpFzmUBhgaU3jY5_kernRW&p=90759a45d4995be006be9b7c547a&newp=8c769a47cd9d50fe08e2947c5c4292695d0fc20e3ddcda01298ffe0cc4241a1a1a3aecbf2c261104d3c77e6700ab4a57e0f53c783d0034f1f689df08d2ecce7e34d63665&s=f05fb18fe7e5de06&user=baidu&fm=sc&query=windows+ping+localhost+%3A%3A1&qid=b2a232ff00233ded&p1=1
文章链接:
https://www.zywvvd.com/notes/system/windows/localhost-post-slow/localhost-post-slow/