You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

手机客户端无法连接本地Python HTTP服务器问题求助

问题解决:Python HTTP服务器无法被手机访问

核心原因

你的服务器绑定了localhost(即127.0.0.1),这个地址仅允许本机访问,局域网内的手机无法连接。而VS Code的Live Server默认绑定0.0.0.0(监听所有网络接口),所以能被手机正常访问。

分步解决方案

1. 修改服务器绑定地址

将代码中的ip变量从"localhost"改为"0.0.0.0",让服务器监听所有可用的网络接口:

# 原代码
ip = "localhost"
# 修改后
ip = "0.0.0.0"

2. 获取电脑的局域网IP

在Linux终端执行以下命令查看本机局域网IP:

hostname -I

会输出类似192.168.1.100的地址,手机浏览器需要访问http://[你的局域网IP]:9000才能打开共享内容。

3. 验证文件夹权限

确保共享的文件夹及其所有父目录有读取权限,可通过以下命令设置(替换为你的文件夹路径):

chmod -R o+r /path/to/your/shared/folder
chmod o+x /path/to/your/shared/folder

-R表示递归处理子目录,o+r赋予其他用户读取权限,o+x确保其他用户能进入该目录。

4. 开放Linux防火墙端口

如果系统启用了防火墙,需要允许9000端口的TCP流量:

# 对于ufw防火墙
sudo ufw allow 9000/tcp
# 对于firewalld
sudo firewall-cmd --add-port=9000/tcp --permanent
sudo firewall-cmd --reload

修改后的完整代码

# Chicken Server v1.0 by Rene Geni
import webbrowser as wb
from tkinter import *
import http.server
import socketserver
import os
import socket

# Define the IP address and port for the server
ip = "0.0.0.0"  # 修改为监听所有接口
port = 9000

# Create a custom request handler that disables caching
class NoCacheRequestHandler(http.server.SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header(
            'Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
        self.send_header('Pragma', 'no-cache')
        super().end_headers()

# Function to start the server
def start_server():
    target_path = text_field.get()
    os.chdir(target_path)
    with socketserver.TCPServer((ip, port), NoCacheRequestHandler) as httpd:
        # 获取本机局域网IP用于提示
        local_ip = socket.gethostbyname(socket.gethostname())
        print(f'Serving directory "{target_path}" at:')
        print(f'本地访问: http://localhost:{port}')
        print(f'局域网访问: http://{local_ip}:{port}')
        wb.open(f"http://localhost:{port}")
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            pass

# GUI logic
window = Tk()
window.title("Chicken Server")
greeting = Label(text="Enter directory path")
text_field = Entry(width="30")
submit = Button(text="Start server", command=start_server)
message = Label(text="To close the server, just close the window")
greeting.pack()
text_field.pack()
submit.pack()
message.pack()
window.mainloop()

内容的提问来源于stack exchange,提问作者Iwegbu Jeddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 20:55:22