forked from quasar/Quasar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHostsManager.cs
63 lines (54 loc) · 1.89 KB
/
HostsManager.cs
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
61
62
63
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
namespace Quasar.Common.DNS
{
public class HostsManager
{
public bool IsEmpty => _hosts.Count == 0;
private readonly Queue<Host> _hosts = new Queue<Host>();
public HostsManager(List<Host> hosts)
{
foreach(var host in hosts)
_hosts.Enqueue(host);
}
public Host GetNextHost()
{
var temp = _hosts.Dequeue();
_hosts.Enqueue(temp); // add to the end of the queue
temp.IpAddress = ResolveHostname(temp);
return temp;
}
private static IPAddress ResolveHostname(Host host)
{
if (string.IsNullOrEmpty(host.Hostname)) return null;
IPAddress ip;
if (IPAddress.TryParse(host.Hostname, out ip))
{
if (ip.AddressFamily == AddressFamily.InterNetworkV6)
{
if (!Socket.OSSupportsIPv6) return null;
}
return ip;
}
var ipAddresses = Dns.GetHostEntry(host.Hostname).AddressList;
foreach (IPAddress ipAddress in ipAddresses)
{
switch (ipAddress.AddressFamily)
{
case AddressFamily.InterNetwork:
return ipAddress;
case AddressFamily.InterNetworkV6:
/* Only use resolved IPv6 if no IPv4 address available,
* otherwise it could be possible that the router the client
* is using to connect to the internet doesn't support IPv6.
*/
if (ipAddresses.Length == 1)
return ipAddress;
break;
}
}
return ip;
}
}
}