|
15 | 15 | #include <netinet/tcp.h> |
16 | 16 | #include <sys/socket.h> |
17 | 17 |
|
| 18 | +#include <cerrno> |
18 | 19 | #include <cstring> |
19 | 20 |
|
20 | 21 | #include "gmock/gmock.h" |
@@ -205,12 +206,26 @@ TEST_P(SocketInetLoopbackIsolatedTest, TCPFinWait2Test) { |
205 | 206 | ASSERT_THAT(bind(conn_fd2.get(), AsSockAddr(&conn_bound_addr), conn_addrlen), |
206 | 207 | SyscallFailsWithErrno(EADDRINUSE)); |
207 | 208 |
|
208 | | - // Sleep for a little over the linger timeout to reduce flakiness in |
209 | | - // save/restore tests. |
210 | | - absl::SleepFor(absl::Seconds(kTCPLingerTimeout + 2)); |
211 | | - |
212 | | - ASSERT_THAT(bind(conn_fd2.get(), AsSockAddr(&conn_bound_addr), conn_addrlen), |
213 | | - SyscallSucceeds()); |
| 209 | + // Sleep for the linger timeout to allow the FIN_WAIT2 timer to expire. |
| 210 | + absl::SleepFor(absl::Seconds(kTCPLingerTimeout)); |
| 211 | + |
| 212 | + // Verify that we can bind and connect to the address. |
| 213 | + // Try multiple times to make the test robust against timing variation. |
| 214 | + constexpr int kMaxAttempts = 5; |
| 215 | + int attempts = 0; |
| 216 | + while (true) { |
| 217 | + if (bind(conn_fd2.get(), AsSockAddr(&conn_bound_addr), conn_addrlen) >= 0) { |
| 218 | + break; // Bind Succeeded. |
| 219 | + } |
| 220 | + if (errno != EADDRINUSE) { |
| 221 | + FAIL() << "bind failed with unexpected errno: " << errno; |
| 222 | + } |
| 223 | + attempts++; |
| 224 | + if (attempts >= kMaxAttempts) { |
| 225 | + FAIL() << "bind failed after " << attempts << " attempts"; |
| 226 | + } |
| 227 | + absl::SleepFor(absl::Seconds(1)); |
| 228 | + } |
214 | 229 |
|
215 | 230 | // Close the `accepted` end otherwise connect can return ECONNREFUSED. |
216 | 231 | constexpr int kTCPLingerTimeout0 = 0; |
|
0 commit comments