Skip to content

Commit 847c0ce

Browse files
authored
Fix UDPSocket broadcast spec to not use connect (#16165)
AFAICT, calling `connect` is only required because we bind the server to the loopback interface that won't receive broadcasted messages otherwise. For example, on my Linux computer, the loopback interface doesn't have BROADCAST traffic enabled (no MULTICAST). We can however start a regular UDP server and a UDP client socket with `SO_BROADCAST`, then call `sendto` to send a message to the broadcast address.
1 parent 46661e2 commit 847c0ce

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

spec/std/socket/udp_socket_spec.cr

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -186,19 +186,31 @@ describe UDPSocket, tags: "network" do
186186
end
187187
end
188188

189-
{% if flag?(:linux) || flag?(:win32) %}
189+
{% if flag?(:darwin) %}
190+
# Fails since macOS Sequoia (version 15) with EHOSTUNREACH. The ability to
191+
# send UDP broadcasts might need extra requirements.
192+
pending "sends broadcast message"
193+
{% else %}
190194
it "sends broadcast message" do
191-
port = unused_local_tcp_port
195+
server = UDPSocket.new(Socket::Family::INET)
196+
server.bind("0.0.0.0", 0)
197+
addr = Socket::IPAddress.new("255.255.255.255", server.local_address.port)
192198

193199
client = UDPSocket.new(Socket::Family::INET)
194-
client.bind("localhost", 0)
195200
client.broadcast = true
196201
client.broadcast?.should be_true
197-
client.connect("255.255.255.255", port)
198-
client.send("broadcast").should eq(9)
202+
203+
client.send("broadcast", to: addr).should eq(9)
199204
client.close
205+
206+
server.read_timeout = 1.second
207+
begin
208+
message, _ = server.receive
209+
message.should eq("broadcast")
210+
rescue IO::TimeoutError
211+
# Since this test doesn't run over the loopback interface, this test
212+
# fails when there is a firewall in use. Don't fail in that case.
213+
end
200214
end
201-
{% else %}
202-
pending "sends broadcast message"
203215
{% end %}
204216
end

0 commit comments

Comments
 (0)