Skip to content

Commit 1dc14b3

Browse files
amitmurthyararslan
authored andcommitted
fix listenany to return correct port number for porthint of 0
Ref #21818 (cherry picked from commit 2272036)
1 parent 8c812ef commit 1dc14b3

File tree

3 files changed

+25
-26
lines changed

3 files changed

+25
-26
lines changed

base/distributed/cluster.jl

+2-9
Original file line numberDiff line numberDiff line change
@@ -153,15 +153,8 @@ function start_worker(out::IO, cookie::AbstractString)
153153
init_worker(cookie)
154154
interface = IPv4(LPROC.bind_addr)
155155
if LPROC.bind_port == 0
156-
addr = Base.InetAddr(interface, 0)
157-
sock = Base.TCPServer()
158-
if bind(sock, addr) && Base.trylisten(sock) == 0
159-
_addr, port = Base._sockname(sock, true)
160-
LPROC.bind_port = port
161-
else
162-
close(sock)
163-
error("no ports available")
164-
end
156+
(port, sock) = listenany(interface, UInt16(0))
157+
LPROC.bind_port = port
165158
else
166159
sock = listen(interface, LPROC.bind_port)
167160
end

base/socket.jl

+4
Original file line numberDiff line numberDiff line change
@@ -826,6 +826,10 @@ function listenany(host::IPAddr, default_port)
826826
while true
827827
sock = TCPServer()
828828
if bind(sock, addr) && trylisten(sock) == 0
829+
if default_port == 0
830+
_addr, port = _sockname(sock, true)
831+
return (port, sock)
832+
end
829833
return (addr.port, sock)
830834
end
831835
close(sock)

test/socket.jl

+19-17
Original file line numberDiff line numberDiff line change
@@ -69,27 +69,29 @@ end
6969
# test show() function for UDPSocket()
7070
@test repr(UDPSocket()) == "UDPSocket(init)"
7171

72-
port = Channel(1)
7372
defaultport = rand(2000:4000)
74-
tsk = @async begin
75-
p, s = listenany(defaultport)
76-
put!(port, p)
77-
sock = accept(s)
78-
# test write call
79-
write(sock,"Hello World\n")
80-
81-
# test "locked" println to a socket
82-
@sync begin
83-
for i in 1:100
84-
@async println(sock, "a", 1)
73+
for testport in [0, defaultport]
74+
port = Channel(1)
75+
tsk = @async begin
76+
p, s = listenany(testport)
77+
put!(port, p)
78+
sock = accept(s)
79+
# test write call
80+
write(sock,"Hello World\n")
81+
82+
# test "locked" println to a socket
83+
@sync begin
84+
for i in 1:100
85+
@async println(sock, "a", 1)
86+
end
8587
end
88+
close(s)
89+
close(sock)
8690
end
87-
close(s)
88-
close(sock)
91+
wait(port)
92+
@test readstring(connect(fetch(port))) == "Hello World\n" * ("a1\n"^100)
93+
wait(tsk)
8994
end
90-
wait(port)
91-
@test readstring(connect(fetch(port))) == "Hello World\n" * ("a1\n"^100)
92-
wait(tsk)
9395

9496
mktempdir() do tmpdir
9597
socketname = is_windows() ? ("\\\\.\\pipe\\uv-test-" * randstring(6)) : joinpath(tmpdir, "socket")

0 commit comments

Comments
 (0)