-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathIPEndPointProvider.cs
More file actions
60 lines (53 loc) · 1.88 KB
/
IPEndPointProvider.cs
File metadata and controls
60 lines (53 loc) · 1.88 KB
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
51
52
53
54
55
56
57
58
59
60
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace SharpProxy
{
public static class IPEndPointProvider
{
private static readonly Dictionary<string, IPAddress> _cache = new Dictionary<string, IPAddress>();
private static readonly Dictionary<string, Task<IPAddress>> _retrieving = new Dictionary<string, Task<IPAddress>>();
async public static Task<IPEndPoint> Get(string host, int port)
{
lock (_cache)
{
if (_cache.ContainsKey(host))
return new IPEndPoint(_cache[host], port);
}
Task<IPAddress> addressTask = null;
lock (_retrieving)
{
if (_retrieving.ContainsKey(host))
{
addressTask = _retrieving[host];
}
else
{
addressTask = Dns.GetHostAddressesAsync(host).ContinueWith(task =>
{
IPAddress newIpAddress = null;
if (!task.IsFaulted && task.Result != null)
newIpAddress = task.Result.FirstOrDefault();
lock (_cache)
{
_cache[host] = newIpAddress;
}
return newIpAddress;
});
_retrieving[host] = addressTask;
}
}
var ipAddress = await addressTask;
if (ipAddress == null)
return null;
return new IPEndPoint(ipAddress, port);
}
private static void DnsResolutionError()
{
if (Debugger.IsAttached)
Debugger.Break();
}
}
}