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
This commit is contained in:
Nick Brown
2023-03-22 10:48:33 -07:00
committed by gVisor bot
parent f8a73a7d1a
commit 1063b2a08e
+4 -3
View File
@@ -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)));