-
Notifications
You must be signed in to change notification settings - Fork 273
/
Copy pathLibPcapSafeNativeMethods.Resolver.cs
87 lines (76 loc) · 2.46 KB
/
LibPcapSafeNativeMethods.Resolver.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Copyright 2020-2021 Ayoub Kaanich <[email protected]>
//
// SPDX-License-Identifier: MIT
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
namespace SharpPcap.LibPcap
{
/// <summary>
/// Per http://msdn.microsoft.com/en-us/ms182161.aspx
/// </summary>
internal static partial class LibPcapSafeNativeMethods
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetDllDirectory(string lpPathName);
static LibPcapSafeNativeMethods()
{
if (
#if NET6_0_OR_GREATER
OperatingSystem.IsWindows()
#else
RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
#endif
)
{
SetDllDirectory(Path.Combine(Environment.SystemDirectory, "Npcap"));
}
else
{
RegisterResolver();
}
StringEncoding = ConfigureStringEncoding();
}
/// <summary>
/// The class NativeLibrary is only available since .NET Core 3.0
/// It's not available in .NET Framework,
/// but that does not affect us since we would use the Windows dll name wpcap
/// </summary>
private static void RegisterResolver()
{
NativeLibraryHelper.SetDllImportResolver(typeof(LibPcapSafeNativeMethods).Assembly, Resolver);
}
public static IntPtr Resolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
{
if (libraryName != PCAP_DLL)
{
// Use default resolver
return IntPtr.Zero;
}
var names = new List<string>();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
names.Add("libpcap.so");
names.Add("libpcap.so.0");
names.Add("libpcap.so.0.8");
names.Add("libpcap.so.1");
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
names.Add("libpcap.dylib");
}
foreach (var name in names)
{
if (NativeLibraryHelper.TryLoad(name, out var handle))
{
return handle;
}
}
return IntPtr.Zero;
}
}
}