Repository navigation
Expand file tree
/
Copy pathAddressCache.cs
More file actions
50 lines (46 loc) · 1.46 KB
/
Copy pathAddressCache.cs
File metadata and controls
50 lines (46 loc) · 1.46 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
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Microsoft.Extensions.Caching.Memory;
namespace Opserver.Helpers
{
public class AddressCache
{
public IMemoryCache MemCache { get; }
public AddressCache(IMemoryCache cache)
{
MemCache = cache;
}
public List<IPAddress> GetHostAddresses(string hostOrIp)
{
return MemCache.GetSet<List<IPAddress>>("host-ip-cache-" + hostOrIp, (_, __) =>
{
try
{
return IPAddress.TryParse(hostOrIp, out var ip)
? new List<IPAddress> { ip }
: Dns.GetHostAddresses(hostOrIp).ToList();
}
catch
{
return new List<IPAddress>();
}
}, 10.Hours(), 24.Hours());
}
public string GetHostName(string ip)
{
return MemCache.GetSet<string>("host-name-cache-" + ip, (_, __) =>
{
try
{
var entry = Dns.GetHostEntry(ip);
return entry != null ? entry.HostName.Split(StringSplits.Period)[0] : "Unknown";
}
catch
{
return "Unknown";
}
}, 10.Minutes(), 24.Hours());
}
}
}