You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python http.server局域网访问故障:仅本机可通过localhost/127.0.0.1访问

问题原因与解决方案:局域网无法访问Python http.server服务

Hey there, let's break down why your server isn't accessible over the LAN and how to fix it:

问题原因

The core issue is right here in your code:

hostName = "localhost"

When you set the hostname to "localhost", the HTTPServer binds exclusively to the 127.0.0.1 loopback address. This address only accepts connections from the same machine running the server—devices on your local network can't reach it at all.

解决方案

Follow these steps to make your server accessible to other devices on the LAN:

1. Update the hostname to listen on all network interfaces

Change hostName to "0.0.0.0". This tells the server to listen on all available network interfaces of your machine, including your local LAN IP address.

2. Allow incoming connections on port 9000

Your firewall is likely blocking external requests to port 9000. Here's how to open it:

  • Windows: Open Windows Defender Firewall → Advanced Settings → Inbound Rules → New Rule → Port → Enter 9000 → Allow the connection.
  • macOS: Go to System Settings → Network → Firewall → Options → Add a rule allowing incoming connections on port 9000.
  • Linux: Use sudo ufw allow 9000/tcp (if using UFW) or configure iptables to allow traffic on port 9000.

3. Find your local LAN IP address

Other devices will need this IP to connect to your server:

  • Windows: Run ipconfig in Command Prompt, look for the IPv4 address under your active network adapter (Ethernet/Wi-Fi).
  • macOS/Linux: Run ifconfig or ip addr in Terminal, find the address starting with 192.168.x.x or 10.x.x.x.

4. Test access from another device

On a LAN device, open a browser and navigate to http://[your-lan-ip]:9000—it should load your server's response now.

Modified Code Example

Here's your updated code with the fix, plus a handy function to auto-detect and print your LAN IP:

from http.server import BaseHTTPRequestHandler, HTTPServer
import socket

# Listen on all network interfaces
hostName = "0.0.0.0"
hostPort = 9000

class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):
        path = self.path
        print(f"Requested path: {path}")
        referer = self.headers.get('Referer')
        print(f"Referer: {referer}")
        
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        
        # Replace this with your actual HTML content
        html_content = "<h1>Hello from your LAN-accessible server!</h1>"
        self.wfile.write(bytes(html_content, "utf-8"))

def get_local_lan_ip():
    """Helper function to get the machine's LAN IP address"""
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # Connect to a dummy external address to determine the active interface
        s.connect(("8.8.8.8", 80))
        lan_ip = s.getsockname()[0]
    except Exception:
        lan_ip = "127.0.0.1"
    finally:
        s.close()
    return lan_ip

myServer = HTTPServer((hostName, hostPort), MyServer)
lan_ip = get_local_lan_ip()

print(f"Server Started!")
print(f"Local access: http://localhost:{hostPort}")
print(f"LAN access: http://{lan_ip}:{hostPort}")

try:
    myServer.serve_forever()
except KeyboardInterrupt:
    print("\nShutting down server...")

myServer.server_close()
print(f"Server Stopped - {hostName}:{hostPort}")

Extra Notes

  • Avoid using str as a variable name—it's a built-in Python type, and reusing it can cause unexpected bugs. I replaced it with html_content in the example.
  • If you still can't connect, check your router settings. Some routers enable AP Isolation by default, which blocks devices on the same network from communicating with each other. Disable this feature if needed.

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

火山引擎 最新活动