Change the NetworkTesterTest.ClientServer test to use a random port number to avoid collisions

Bug: webrtc:15575
Change-Id: Ied0bdc79d52edd0d919be007798135c1c6b1f98b
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/323820
Reviewed-by: Harald Alvestrand <hta@webrtc.org>
Reviewed-by: Björn Terelius <terelius@webrtc.org>
Commit-Queue: Björn Terelius <terelius@webrtc.org>
Cr-Commit-Position: refs/heads/main@{#40966}
diff --git a/rtc_tools/network_tester/BUILD.gn b/rtc_tools/network_tester/BUILD.gn
index e33a3c0..efe2123 100644
--- a/rtc_tools/network_tester/BUILD.gn
+++ b/rtc_tools/network_tester/BUILD.gn
@@ -86,6 +86,7 @@
     deps = [
       ":network_tester",
       "../../rtc_base:gunit_helpers",
+      "../../rtc_base:random",
       "../../rtc_base:threading",
       "../../test:fileutils",
       "../../test:test_support",
diff --git a/rtc_tools/network_tester/network_tester_unittest.cc b/rtc_tools/network_tester/network_tester_unittest.cc
index 60b34e4..ea0ebf9 100644
--- a/rtc_tools/network_tester/network_tester_unittest.cc
+++ b/rtc_tools/network_tester/network_tester_unittest.cc
@@ -13,6 +13,7 @@
 #include <string>
 
 #include "rtc_base/gunit.h"
+#include "rtc_base/random.h"
 #include "rtc_tools/network_tester/test_controller.h"
 #include "test/gtest.h"
 #include "test/testsupport/file_utils.h"
@@ -20,15 +21,22 @@
 namespace webrtc {
 
 TEST(NetworkTesterTest, ServerClient) {
+  // Use a unique port rather than a hard-coded one to avoid collision when
+  // running the test in parallel in stress runs. Skipping all reserved ports.
+  const int MIN_PORT = 49152;
+  const int MAX_PORT = 65535;
+  int port = webrtc::Random(rtc::TimeMicros()).Rand(MIN_PORT, MAX_PORT);
+
   rtc::AutoThread main_thread;
+
   TestController client(
       0, 0, webrtc::test::ResourcePath("network_tester/client_config", "dat"),
       webrtc::test::OutputPath() + "client_packet_log.dat");
   TestController server(
-      9090, 9090,
+      port, port,
       webrtc::test::ResourcePath("network_tester/server_config", "dat"),
       webrtc::test::OutputPath() + "server_packet_log.dat");
-  client.SendConnectTo("127.0.0.1", 9090);
+  client.SendConnectTo("127.0.0.1", port);
   EXPECT_TRUE_WAIT(server.IsTestDone() && client.IsTestDone(), 2000);
 }
 
diff --git a/rtc_tools/network_tester/test_controller.cc b/rtc_tools/network_tester/test_controller.cc
index 6fe83fd..3d9af38 100644
--- a/rtc_tools/network_tester/test_controller.cc
+++ b/rtc_tools/network_tester/test_controller.cc
@@ -43,6 +43,7 @@
     udp_socket_ =
         std::unique_ptr<rtc::AsyncPacketSocket>(socket_factory_.CreateUdpSocket(
             rtc::SocketAddress(rtc::GetAnyIP(AF_INET), 0), min_port, max_port));
+    RTC_CHECK(udp_socket_ != nullptr);
     udp_socket_->SignalReadPacket.connect(this, &TestController::OnReadPacket);
   });
 }