| | | 1 | | using System.Net; |
| | | 2 | | using System.Net.Sockets; |
| | | 3 | | |
| | | 4 | | namespace WireMock.Http |
| | | 5 | | { |
| | | 6 | | /// <summary> |
| | | 7 | | /// The ports. |
| | | 8 | | /// </summary> |
| | | 9 | | public static class PortUtil |
| | | 10 | | { |
| | | 11 | | /// <summary> |
| | | 12 | | /// The find free TCP port. |
| | | 13 | | /// </summary> |
| | | 14 | | /// <returns> |
| | | 15 | | /// The <see cref="int"/>. |
| | | 16 | | /// </returns> |
| | | 17 | | /// <remarks>see http://stackoverflow.com/questions/138043/find-the-next-tcp-port-in-net.</remarks> |
| | | 18 | | public static int FindFreeTcpPort() |
| | 16 | 19 | | { |
| | 16 | 20 | | TcpListener tcpListener = null; |
| | | 21 | | try |
| | 16 | 22 | | { |
| | 16 | 23 | | tcpListener = new TcpListener(IPAddress.Loopback, 0); |
| | 16 | 24 | | tcpListener.Start(); |
| | | 25 | | |
| | 16 | 26 | | return ((IPEndPoint)tcpListener.LocalEndpoint).Port; |
| | | 27 | | } |
| | | 28 | | finally |
| | 16 | 29 | | { |
| | 16 | 30 | | tcpListener?.Stop(); |
| | 16 | 31 | | } |
| | 16 | 32 | | } |
| | | 33 | | } |
| | | 34 | | } |