net.Listen is unable to detect port conflict on Windows

81 views
Skip to first unread message

Nicola Murino

unread,
Mar 22, 2021, 6:00:11 AM3/22/21
to golang-nuts
Hi,

I recently discovered this strange behaviour, Windows allows the coexistence of three types of sockets on the same transport-layer service port, for example, 127.0.0.1:8080, [::1]:8080 and [::ffff:0.0.0.0]:8080.

So if you use something like:

net.Listen("tcp", fmt.Sprintf(":%d", port)

and another program already uses the same port using an IPv4 address, Listen will not fail.

If instead you use:

net.Listen("tcp4", fmt.Sprintf(":%d", port)

it will fail as expected.

Based on the following issues, this is the intended behaviour 


so a Go listener behaves differently based on the operating system and this could cause unexpected bug reports from Windows users.

In my program I want to listen on both IPv4 and IPv6 (if available) and so I use "tcp" as address.

To be able to detect port conflict with other programs, I have to do something like this:

if runtime.GOOS != osWindows {
return
}
listener, err := net.Listen("tcp4", fmt.Sprintf(":%d", port))
if err != nil {
os.Exit(1)
}
listener.Close()

before starting net.Listen with "tcp" address.

So all of you use a similar fix? Do you know a cleaner solution? 

I would have expected such a workaround within Go itself if it is the only way.

Based on the above issues, python had the same problem in the past but it seems now fixed in recent versions.

Thank you
Nicola

Reply all
Reply to author
Forward
0 new messages