-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathIpDetectionService.cs
59 lines (52 loc) · 1.7 KB
/
IpDetectionService.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
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
namespace fs2ff
{
public class IpDetectionService : IHostedService
{
private const int Port = 63093;
public event Action<IPAddress>? NewIpDetected;
public async Task StartAsync(CancellationToken cancellationToken)
{
await Task.Run(async () =>
{
try
{
using var udpClient = new UdpClient(Port, IPAddress.Any.AddressFamily);
while (!cancellationToken.IsCancellationRequested)
{
var result = await udpClient.ReceiveAsync();
var text = Encoding.ASCII.GetString(result.Buffer);
if (IsForeFlightGdl90(text))
{
NewIpDetected?.Invoke(result.RemoteEndPoint.Address);
}
}
}
catch (SocketException e)
{
Console.Error.WriteLine(e);
}
}, cancellationToken);
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
private static bool IsForeFlightGdl90(string text)
{
try
{
return JsonDocument.Parse(text).RootElement.TryGetProperty("App", out var app) &&
app.GetString() == "ForeFlight";
}
catch (Exception)
{
return false;
}
}
}
}