From 9e2b411a509227d76802457adffd3b63044bba2a Mon Sep 17 00:00:00 2001 From: Alex Konradi Date: Tue, 3 Jan 2023 09:43:35 -0800 Subject: [PATCH] Connect before closing the destination socket to acquire different port In the ConnectWriteToInvalidPort test case, the target socket is closed before the source socket sends data to generate and then verify reception of an ICMP error packet. If the target socket is closed before an outgoing port number is picked for the source socket, the source socket might be assigned the same port number for sending as its destination. The result is that the source socket receives the packet it sends and so no error is generated. This results in test flakiness, though with very low probability. Fixes #8338 PiperOrigin-RevId: 499244574 --- test/syscalls/linux/udp_socket.cc | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/test/syscalls/linux/udp_socket.cc b/test/syscalls/linux/udp_socket.cc index 3a5577bdc..f08a2adb6 100644 --- a/test/syscalls/linux/udp_socket.cc +++ b/test/syscalls/linux/udp_socket.cc @@ -385,11 +385,14 @@ TEST_P(UdpSocketTest, ConnectWriteToInvalidPort) { ASSERT_THAT(getsockname(s.get(), addr, &addrlen), SyscallSucceeds()); EXPECT_EQ(addrlen, addrlen_); EXPECT_NE(*Port(&addr_storage), 0); - ASSERT_THAT(close(s.release()), SyscallSucceeds()); - - // Now connect to the port that we just released. This should generate an - // ECONNREFUSED error. + // Connect to the same address. This won't send data yet but will ensure that + // the local port chosen for the connecting socket is different from the + // remote port, since it is still in use. ASSERT_THAT(connect(sock_.get(), addr, addrlen_), SyscallSucceeds()); + + // Now free the destination port and then send a packet to it. This should + // generate an ECONNREFUSED error. + ASSERT_THAT(close(s.release()), SyscallSucceeds()); char buf[512]; RandomizeBuffer(buf, sizeof(buf)); // Send from sock_ to an unbound port.