| | | 1 | | using System.Net; |
| | | 2 | | using System.Net.Sockets; |
| | | 3 | | using System.Text.RegularExpressions; |
| | | 4 | | |
| | | 5 | | namespace WireMock.Util |
| | | 6 | | { |
| | | 7 | | /// <summary> |
| | | 8 | | /// Port Utility class |
| | | 9 | | /// </summary> |
| | | 10 | | public static class PortUtils |
| | | 11 | | { |
| | 1 | 12 | | private static readonly Regex UrlDetailsRegex = new Regex(@"^((?<proto>\w+)://)(?<host>[^/]+?):(?<port>\d+)\/?$" |
| | | 13 | | |
| | | 14 | | /// <summary> |
| | | 15 | | /// Finds a free TCP port. |
| | | 16 | | /// </summary> |
| | | 17 | | /// <remarks>see http://stackoverflow.com/questions/138043/find-the-next-tcp-port-in-net.</remarks> |
| | | 18 | | public static int FindFreeTcpPort() |
| | 46 | 19 | | { |
| | 46 | 20 | | TcpListener tcpListener = null; |
| | | 21 | | try |
| | 46 | 22 | | { |
| | 46 | 23 | | tcpListener = new TcpListener(IPAddress.Loopback, 0); |
| | 46 | 24 | | tcpListener.Start(); |
| | | 25 | | |
| | 46 | 26 | | return ((IPEndPoint)tcpListener.LocalEndpoint).Port; |
| | | 27 | | } |
| | | 28 | | finally |
| | 46 | 29 | | { |
| | 46 | 30 | | tcpListener?.Stop(); |
| | 46 | 31 | | } |
| | 46 | 32 | | } |
| | | 33 | | |
| | | 34 | | /// <summary> |
| | | 35 | | /// Extract the protocol, host and port from a URL. |
| | | 36 | | /// </summary> |
| | | 37 | | public static bool TryExtract(string url, out string protocol, out string host, out int port) |
| | 98 | 38 | | { |
| | 98 | 39 | | protocol = null; |
| | 98 | 40 | | host = null; |
| | 98 | 41 | | port = default(int); |
| | | 42 | | |
| | 98 | 43 | | Match m = UrlDetailsRegex.Match(url); |
| | 98 | 44 | | if (m.Success) |
| | 96 | 45 | | { |
| | 96 | 46 | | protocol = m.Groups["proto"].Value; |
| | 96 | 47 | | host = m.Groups["host"].Value; |
| | | 48 | | |
| | 96 | 49 | | return int.TryParse(m.Groups["port"].Value, out port); |
| | | 50 | | } |
| | | 51 | | |
| | 2 | 52 | | return false; |
| | 98 | 53 | | } |
| | | 54 | | } |
| | | 55 | | } |