Mac 的 localhost & 127.0.0.1 的5000端口拒绝访问
最近开发 Python 应用, 使用 Flask框架, 启动 app 默认开启 5000 端口. 如下:
* Debugger is active!
* Debugger PIN: 529-552-853
(9079) wsgi starting up on http://127.0.0.1:5000
一开始的时候, 发现 localhost:5000 无法访问:
只能 127.0.0.1:5000 访问, 虽然无法解释, 但是启动日志写的 127.0.0.1:5000 也能暂时这么使用.
可是, 很快就发现了新问题, 一旦任何一个文件更改, 就会触发app重新load, 然后重启, 这个时候, 就发现连 127.0.0.1:5000 也无法访问了:
于是我想到了之前遇到的问题: 由于某些cookie过大, 导致某些Python框架处理不过来, 直接不能正常返回. 于是 - 我清理缓存 -> Chrome 浏览器 -> More Tools -> Clear Browsing Data -> Cookies and Site Data.
问题得以暂时解决. 可是, 这带来了副作用-> 每次清理完, 很多登录过的账号, 都要重新登录. 比如 chat.openai.com 和 公司里面的很多工具. 烦.
于是, 想去弄明白, 到底哪里出了问题. 我重新访问 127.0.0.1:5000, 然后去仔细观察请求/回应数据, 发现了端倪:
AirTunes/675.4.1 这是啥?
诊断
然后看谁打开了5000端口:
eric@host % sudo lsof -i -n -P | grep 5000
Password:
ControlCe 539 eric 7u IPv4 0xbe799013704c3c99 0t0 TCP *:5000 (LISTEN)
ControlCe 539 eric 8u IPv6 0xbe799009db509931 0t0 TCP *:5000 (LISTEN)
虽然不能看到完全的进程名, 但是可以看到进程号: 539. 然后打开 Activity Monitor, 然后查看这个进程, 然后看到进程名字是: Control Center, 还有那个熟悉的图标.
于是, 我尝试杀死这个进程, 它又自动重启了, 同时我启动了 Flask app, 于是这次我看到 5000 端口在 * 上面被 Control Center 占用了, 127.0.0.1 的5000端口, 被 Flask app 占用了:
eric@host % sudo lsof -i -n -P | grep 5000
ControlCe 9926 eric 7u IPv4 0xbe79901362e29b39 0t0 TCP *:5000 (LISTEN)
ControlCe 9926 eric 8u IPv6 0xbe799009db4de1b1 0t0 TCP *:5000 (LISTEN)
Python 9948 eric 8u IPv4 0xbe799013679bab39 0t0 TCP 127.0.0.1:5000 (LISTEN)
解决办法
顺着上面找到的关键字, 我们Google 一下, 第一个就是这个官方问答: https://developer.apple.com/forums/thread/682332
原来是 Control Center 里的 AirPlay Receiver 监听在这个端口.
勾掉这个, 就发现不在监听 5000 端口了:
eric@host % sudo lsof -i -n -P | grep 5000
Python 9948 eric 8u IPv4 0xbe799013679bab39 0t0 TCP 127.0.0.1:5000 (LISTEN)
当然, 从另外一个角度, 我们只要改改 Flask 的默认端口, 也能达到这个效果:
_app, _socketio = create_app()
_socketio.run(_app, host='0.0.0.0', port=5050)