Skip to content

Commit 7271623

Browse files
committed
[dotnet] Dispose socket object to find free tcp port
1 parent 1e7152c commit 7271623

File tree

1 file changed

+8
-13
lines changed

1 file changed

+8
-13
lines changed

dotnet/src/webdriver/Internal/PortUtilities.cs

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
// under the License.
1818
// </copyright>
1919

20+
using System;
2021
using System.Net;
2122
using System.Net.Sockets;
2223

@@ -33,23 +34,17 @@ public static class PortUtilities
3334
/// <returns>A random, free port to be listened on.</returns>
3435
public static int FindFreePort()
3536
{
36-
// Locate a free port on the local machine by binding a socket to
37-
// an IPEndPoint using IPAddress.Any and port 0. The socket will
38-
// select a free port.
39-
int listeningPort = 0;
40-
Socket portSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
37+
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
38+
4139
try
4240
{
43-
IPEndPoint socketEndPoint = new IPEndPoint(IPAddress.Any, 0);
44-
portSocket.Bind(socketEndPoint);
45-
socketEndPoint = (IPEndPoint)portSocket.LocalEndPoint!;
46-
listeningPort = socketEndPoint.Port;
41+
socket.Bind(new IPEndPoint(IPAddress.Any, 0));
42+
43+
return ((IPEndPoint)socket.LocalEndPoint!).Port;
4744
}
48-
finally
45+
catch (SocketException ex)
4946
{
50-
portSocket.Close();
47+
throw new InvalidOperationException("Unable to find a free port.", ex);
5148
}
52-
53-
return listeningPort;
5449
}
5550
}

0 commit comments

Comments
 (0)