本文最后更新于:2023年12月5日 下午

使用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做地址执行各种任务都快了很多

参考资料



文章链接:
https://www.zywvvd.com/notes/system/windows/localhost-post-slow/localhost-post-slow/


“觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭”

微信二维码

微信支付

支付宝二维码

支付宝支付

windows 10 使用localhost作为地址执行网络请求延迟问题的解决方案
https://www.zywvvd.com/notes/system/windows/localhost-post-slow/localhost-post-slow/
作者
Yiwei Zhang
发布于
2021年5月20日
许可协议