Skip to content

Commit d032774

Browse files
committed
small refactor of RandomPortFinder
1 parent c91c99c commit d032774

File tree

1 file changed

+40
-37
lines changed

1 file changed

+40
-37
lines changed
Lines changed: 40 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,58 @@
1-
using System;
2-
using System.Collections.Concurrent;
3-
using System.Collections.Generic;
4-
using System.Linq;
5-
using System.Net;
6-
using System.Net.Http;
7-
using System.Net.Sockets;
8-
using System.Text;
9-
10-
namespace Ocelot.AcceptanceTests
1+
namespace Ocelot.AcceptanceTests
112
{
3+
using System;
4+
using System.Collections.Concurrent;
5+
using System.Linq;
6+
using System.Net;
7+
using System.Net.Sockets;
8+
129
public static class RandomPortFinder
1310
{
14-
private static readonly int TrialNumber = 100;
15-
private static readonly int BeginPortRange = 20000;
16-
private static readonly int EndPortRange = 45000;
17-
18-
private static Random random = new Random();
19-
private static ConcurrentBag<int> usedPorts = new ConcurrentBag<int>();
11+
private const int TrialNumber = 100;
12+
private const int BeginPortRange = 20000;
13+
private const int EndPortRange = 45000;
14+
private static readonly Random Random = new Random();
15+
private static readonly ConcurrentBag<int> UsedPorts = new ConcurrentBag<int>();
2016

2117
public static int GetRandomPort()
2218
{
23-
int randomPort = 0;
24-
for (int i = 0; i < TrialNumber; i++)
19+
for (var i = 0; i < TrialNumber; i++)
2520
{
26-
randomPort = random.Next(BeginPortRange, EndPortRange);
27-
if (usedPorts.Any(p => p == randomPort))
28-
{
29-
continue;
30-
}
31-
else
32-
{
33-
usedPorts.Add(randomPort);
34-
}
21+
var randomPort = Random.Next(BeginPortRange, EndPortRange);
3522

36-
try
23+
if (!PortInUse(randomPort))
3724
{
38-
IPEndPoint ipe = new IPEndPoint(IPAddress.Loopback, randomPort);
39-
using (var socket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
25+
try
26+
{
27+
return UsePort(randomPort);
28+
}
29+
catch (Exception)
4030
{
41-
socket.Bind(ipe);
42-
socket.Close();
43-
return randomPort;
31+
// ignored
4432
}
4533
}
46-
catch (Exception)
47-
{
48-
continue;
49-
}
5034
}
5135

5236
throw new Exception("Cannot find available port to bind to.");
5337
}
38+
39+
private static int UsePort(int randomPort)
40+
{
41+
UsedPorts.Add(randomPort);
42+
43+
var ipe = new IPEndPoint(IPAddress.Loopback, randomPort);
44+
45+
using (var socket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
46+
{
47+
socket.Bind(ipe);
48+
socket.Close();
49+
return randomPort;
50+
}
51+
}
52+
53+
private static bool PortInUse(int randomPort)
54+
{
55+
return UsedPorts.Any(p => p == randomPort);
56+
}
5457
}
5558
}

0 commit comments

Comments
 (0)