blob: 7c83bf3886df21c81d39ef6a2b0998fecc6b5b9b (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
using System;
using System.Net;
using System.Net.Sockets;
namespace Google.GRPC.Core.Utils
{
public class PortPicker
{
static Random random = new Random();
// TODO: cleanup this code a bit
public static int PickUnusedPort()
{
int port;
do
{
port = random.Next(2000, 50000);
} while(!IsPortAvailable(port));
return port;
}
// TODO: cleanup this code a bit
public static bool IsPortAvailable(int port)
{
bool available = true;
TcpListener server = null;
try
{
IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
server = new TcpListener(ipAddress, port);
server.Start();
}
catch (Exception ex)
{
available = false;
}
finally
{
if (server != null)
{
server.Stop();
}
}
return available;
}
}
}
|