From 1063b2a08ecf618fa9fed6f1ff50b6fe16ba92b9 Mon Sep 17 00:00:00 2001 From: Nick Brown Date: Wed, 22 Mar 2023 10:46:09 -0700 Subject: [PATCH] Connect to bound addr before closing socket The `ConnectAndSendNoReceiver` test tries to setup a scenario in which a socket sends to an address with no listener, asserting on the returned ICMP error. In the existing code, this is done by closing a socket and then connecting/sending to its bound address with another socket. This is flaky because sometimes the system will coincidentally bind the sender to the bound address of the receiver, in which case we won't get the ICMP error. The fix is to connect before the socket is closed (that way the sender will get a different port than the boudn address). PiperOrigin-RevId: 518612786 --- test/syscalls/linux/udp_socket.cc | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/test/syscalls/linux/udp_socket.cc b/test/syscalls/linux/udp_socket.cc index 345301049..8816af529 100644 --- a/test/syscalls/linux/udp_socket.cc +++ b/test/syscalls/linux/udp_socket.cc @@ -797,14 +797,15 @@ TEST_P(UdpSocketTest, SendToAddressOtherThanConnected) { TEST_P(UdpSocketTest, ConnectAndSendNoReceiver) { ASSERT_NO_ERRNO(BindLoopback()); - // Close the socket to release the port so that we get an ICMP error. - ASSERT_THAT(close(bind_.release()), SyscallSucceeds()); - // Connect to loopback:bind_addr_ which should *hopefully* not be bound by an // UDP socket. There is no easy way to ensure that the UDP port is not bound // by another conncurrently running test. *This is potentially flaky*. ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds()); + // Close the socket after connecting to the bound address to make sure `sock_` + // doesn't get auto-bound to the same port. + ASSERT_THAT(close(bind_.release()), SyscallSucceeds()); + char buf[512]; EXPECT_THAT(send(sock_.get(), buf, sizeof(buf), 0), SyscallSucceedsWithValue(sizeof(buf)));