-
Notifications
You must be signed in to change notification settings - Fork 3
/
Reachability .cs
53 lines (43 loc) · 1.62 KB
/
Reachability .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
using MonoTouch.SystemConfiguration;
using System.Threading.Tasks;
namespace GoogleAnalytics
{
public static class Reachability
{
public static bool IsReachableWithoutRequiringConnection(NetworkReachabilityFlags flags)
{
// Is it reachable with the current network configuration?
bool isReachable = (flags & NetworkReachabilityFlags.Reachable) != 0;
// Do we need a connection to reach it?
bool noConnectionRequired = (flags & NetworkReachabilityFlags.ConnectionRequired) == 0;
// Since the network stack will automatically try to get the WAN up, probe that
if ((flags & NetworkReachabilityFlags.IsWWAN) != 0)
noConnectionRequired = true;
return isReachable && noConnectionRequired;
}
// Is the host reachable with the current network configuration
public static bool IsHostReachable(string host)
{
if (string.IsNullOrEmpty(host))
return false;
using (var r = new NetworkReachability(host))
{
NetworkReachabilityFlags flags;
if (r.TryGetFlags(out flags))
{
return IsReachableWithoutRequiringConnection(flags);
}
}
return false;
}
public static Task<bool> IsHostReachableAsync(string host)
{
var tcs = new TaskCompletionSource<bool>();
Task.Run(() =>
{
tcs.SetResult(IsHostReachable(host));
});
return tcs.Task;
}
}
}