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

Go语言视频文件服务器无法在WiFi网络广播问题求助

同一WiFi下移动设备无法访问Go语言视频文件服务器

我用Go编写了一个视频文件服务器,主机本地可正常访问(例如在本机浏览器输入http://192.168.1.100:8080/videos/能正常打开),但同一WiFi网络下的移动设备无法连接。运行环境为Windows系统,项目包含main.go、file_server.go、mdns.go及network_interface.go文件,相关代码如下,恳请协助排查。

main.go

package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
    "path/filepath"
    "strings"
    "time"

    "video-server/auth"
    "video-server/file_server"
    "video-server/mdns"
    "video-server/network_interface"
    "video-server/ui"
)

func main() {
    // Ask for a Username
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter username: ")
    username, _ := reader.ReadString('\n')
    username = strings.TrimSpace(username)

    // Ask for a Password
    fmt.Print("Enter password: ")
    password, _ := reader.ReadString('\n')
    password = strings.TrimSpace(password)

    // Set authentication credentials
    if err := auth.SetCredentials(username, password); err != nil {
        log.Fatalf("Failed to set credentials: %v", err)
    }

    // Get the Wi-Fi adapter IP address
    wifiIP := network_interface.GetWiFiIP()
    if wifiIP == "" {
        fmt.Println("Could not find Wi-Fi IP address")
        return
    }

    // Define the "videos" folder path
    videosFolderPath := filepath.Join("videos")

    // Ensure "videos" folder exists
    if err := ui.CheckAndCreateFolder(videosFolderPath); err != nil {
        fmt.Println("Error creating videos folder:", err)
        return
    }

    // Generate the index.html file
    if err := ui.GenerateIndexHTML(videosFolderPath, wifiIP); err != nil {
        fmt.Println("Error generating index.html:", err)
        return
    }

    // Start the file server in a separate goroutine
    go file_server.StartFileServer()

    // Wait a bit before advertising mDNS to ensure server starts first
    go func() {
        time.Sleep(2 * time.Second)
        mdns.AdvertiseServer(wifiIP) // Use Wi-Fi IP
    }()

    // Keep the main function running
    select {} // Keeps the program alive
}

file_server.go

package file_server

import (
    "fmt"
    "log"
    "net/http"
    "os"
    "path/filepath"
    "video-server/auth"
    "video-server/network_interface"
)

// StartFileServer serves video files from the "videos" folder with authentication
func StartFileServer() {
    // Get the current working directory
    rootDir, err := os.Getwd()
    if err != nil {
        log.Fatalf("Failed to get working directory: %v", err)
    }

    // Define the videos folder path
    videosFolderPath := filepath.Join(rootDir, "videos")

    // Ensure the "videos" folder exists
    if _, err := os.Stat(videosFolderPath); os.IsNotExist(err) {
        err = os.Mkdir(videosFolderPath, os.ModePerm)
        if err != nil {
            log.Fatalf("Failed to create videos folder: %v", err)
        }
        fmt.Println("Created 'videos' folder at:", videosFolderPath)
    } else {
        fmt.Println("Using existing 'videos' folder at:", videosFolderPath)
    }

    // Get the IP address of the Wi-Fi adapter
    wifiIP := network_interface.GetWiFiIP()
    if wifiIP == "" {
        log.Fatal("Could not find Wi-Fi IP address")
    } else {
        fmt.Println("Device Wi-Fi IP address successfully obtained:", wifiIP)
    }

    // Bind the server to all interfaces (0.0.0.0) for broader accessibility
    address := "0.0.0.0:8080"
    fmt.Println("Starting file server on " + address + "/videos")

    // Serve the videos folder with authentication
    fileHandler := auth.BasicAuth(http.StripPrefix("/videos/", http.FileServer(http.Dir(videosFolderPath))))

    // Start the HTTP server directly without ServeMux
    err = http.ListenAndServe(address, fileHandler)
    if err != nil {
        log.Fatal("Error starting file server:", err)
    }
}

mdns.go

package mdns

import (
    "fmt"
    "log"
    "time"

    "github.com/grandcat/zeroconf"
)

// AdvertiseServer advertises the server using mDNS
func AdvertiseServer(wifiIP string) {
    if wifiIP == "" {
        log.Println("Could not find Wi-Fi IP address, skipping mDNS advertisement.")
        return
    }

    // Register the mDNS service
    service, err := zeroconf.Register(
        "WiFi File Server", // Service Name
        "_http._tcp",       // Service Type (HTTP over TCP)
        "local.",           // mDNS Domain (Fixed)
        8080,               // Port
        []string{
            "txtvers=1",
            "path=/videos/",
            "ip=" + wifiIP, // ✅ Explicitly advertise the Wi-Fi IP
        },
        nil, // No need for custom interfaces
    )
    if err != nil {
        log.Println("Error advertising mDNS service:", err)
        return
    }
    defer service.Shutdown() // Keep mDNS running until the program exits

    fmt.Println("mDNS Service is running. Try: http://" + wifiIP + ":8080/videos/")

    // Keep the service running
    for {
        time.Sleep(10 * time.Second) // Keep alive
    }
}

排查步骤

1. 检查Windows防火墙

  • 确认Windows Defender防火墙允许你的Go程序通过专用网络(WiFi属于此类)通信
  • 手动添加入站规则:允许TCP 8080端口的连接,或直接允许该程序的网络访问
  • 临时关闭防火墙测试(测试后恢复),若能访问则说明是防火墙拦截

2. 验证网络连通性

  • 在移动设备上ping主机的WiFi IP(如192.168.1.100),若不通:
    • 确认主机和移动设备在同一WiFi网段
    • 检查路由器是否开启了AP隔离/客户端隔离,开启的话需关闭
  • 用移动设备的端口扫描工具测试192.168.1.100:8080是否开放,若端口不通则说明未正常监听或被拦截

3. 确认服务器监听状态

  • 打开Windows命令提示符,执行:netstat -ano | findstr :8080
  • 检查输出中是否有0.0.0.0:8080的监听记录,且对应的PID是你的Go程序进程
  • 若监听地址是127.0.0.1:8080,说明程序仅绑定本地回环,外部设备无法访问

4. 排查认证逻辑

  • 移动设备访问时是否弹出Basic Auth登录框?若输入正确账号密码仍无法访问,临时注释掉auth.BasicAuth中间件测试,排除认证逻辑问题
  • 确认main.go中设置的账号密码与移动设备输入的一致

5. 路由器设置检查

  • 确认主机的WiFi IP是静态还是动态,若为动态需重新获取当前IP再尝试访问
  • 检查路由器是否限制了设备间的访问规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 16:07:03