My program stops a net.Listener and then creates a new one immediately on the same port. On Linux this works fine, presumably due to SO_REUSEADDR being 1 by default, but on Windows, I get:
bind: Only one usage of each socket address (protocol/network address/port) is normally permitted.
I still get the error though. (Actually, it seems racy. If I time.Sleep(100 * time.Millisecond) between stopping the listener and starting the new one, the error is almost always absent.)
What’s the proper way to be able to reuse a port immediately after closing it? Or, what’s a good way to forcibly close the socket on Windows?
Edit: I found this about UDPConn, but I figure the same discouraging thing could be said of TCPListener: sockets - Get syscall.Handle from a Go *net.UDPConn on Windows? - Stack Overflow. Since I’m not interested in going the unsafe route (or any cgo route) perhaps I should abandon hope and just time.Sleep between restarts…