本文最后更新于:2022年8月10日 上午
使用localhost作为地址执行网络请求时会有2s的延时,这个问题在Linux并不存在,本文分析并提出解决方案。
问题复现
主要体现在windows 下,python 使用 flask 将 localhost 作为地址时有2s延迟
原因分析
问题在于解析localhost时,优先按照ipv6地址解析,这个可以通过ping命令验证:
1 2 3 4 5 C:\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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 C:\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地址前移到最高优先级
修改优先级
1 2 3 4 netsh int ipv6 set prefix ::/96 50 0 netsh int ipv6 set prefix ::ffff:0:0/96 40 1 netsh int ipv6 set prefix ::1/128 10 4 netsh int ipv6 set prefix ::/0 5 5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 C:\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
问题解决
测试
1 2 3 4 5 C:\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做地址执行各种任务都快了很多
参考资料