Go UDP局域网跨PC通信报错:bind: cannot assign requested address及空指针异常
Hey Daniel, let’s work through this issue—this is a really common hurdle when moving Go network apps from local testing to actual LAN communication! Let’s break down the errors and fix them one by one.
This is the root cause of your initial failure, and it’s almost always tied to how your server is binding to a network address:
- Bind to
0.0.0.0instead of a specific IP
When you bind to a specific LAN IP like192.168.11.6, your server will only listen on that exact network interface. If the IP is incorrect, or the interface isn’t active, you’ll get this error. Instead, bind to0.0.0.0(which listens on all available network interfaces) using:addr, err := net.ResolveUDPAddr("udp", ":10001") // Or explicitly use IPv4zero: // addr := &net.UDPAddr{IP: net.IPv4zero, Port: 10001} if err != nil { log.Fatal(err) } conn, err := net.ListenUDP("udp", addr) - Verify your server’s actual LAN IP
Double-check that192.168.11.6is truly the IP of your server machine. Runipconfig(Windows) orip addr(Linux/macOS) to confirm the correct IPv4 address for your local network adapter. - Check for port conflicts
Make sure no other program is using port 10001. On Windows, runnetstat -ano | findstr :10001; on Linux/macOS, uselsof -i :10001to see if the port is occupied.
This panic happens because your code is trying to use the *UDPConn returned by ListenUDP without checking for errors first. If ListenUDP fails (like with the bind error), it returns nil for the connection, and any subsequent call to that nil connection will trigger the panic. Always add error checking immediately after the listen call:
conn, err := net.ListenUDP("udp", addr) if err != nil { log.Fatalf("Failed to start UDP server: %v", err) } defer conn.Close() // Ensure the connection is closed when done
Even after fixing the bind issue, you might still have connectivity problems—here’s what to verify:
- Allow the port through firewalls
Both your server and client machines need to allow UDP traffic on port 10001. On Windows, create an inbound/outbound firewall rule for the port; on Linux, usesudo ufw allow 10001/udp; on macOS, adjust firewall settings in System Preferences. - Client connects to the correct server IP
Make sure your client code is targeting the server’s actual LAN IP (notlocalhostor127.0.0.1). For example:serverAddr, err := net.ResolveUDPAddr("udp", "192.168.11.6:10001") if err != nil { log.Fatal(err) } conn, err := net.DialUDP("udp", nil, serverAddr) - Confirm protocol consistency
Double-check that both server and client are using UDP—mixing TCP and UDP will cause silent failures or errors.
内容的提问来源于stack exchange,提问作者Daniel

