我正在使用 TAP-Windows(来自 OpenVPN 项目)来创建一个界面,如此处和此处所述。我基于第一篇文章中提供的示例代码:
const string UsermodeDeviceSpace = "\\\\.\\Global\\";
string devGuid = GetDeviceGuid();
IntPtr ptr= CreateFile(UsermodeDeviceSpace+devGuid+".tap",
FileAccess.ReadWrite,
FileShare.ReadWrite,
0,
FileMode.Open,
FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
IntPtr.Zero);
int len;
IntPtr pstatus = Marshal.AllocHGlobal(4);
Marshal.WriteInt32(pstatus, 1);
// Set media status to connected
DeviceIoControl (ptr,
TAP_CONTROL_CODE (6, METHOD_BUFFERED), pstatus, 4,
pstatus,
4,
out len,
IntPtr.Zero);
IntPtr ptun = Marshal.AllocHGlobal(12);
Marshal.WriteInt32(ptun, 0, 0x0100030a); // 10.0.0.1, Interface address
Marshal.WriteInt32(ptun, 4, 0x0000030a); // 10.0.0.0, Network
Marshal.WriteInt32(ptun, 8, unchecked((int)0x00ffffff)); // 255.255.255.0, Netmask
// Config TUN
DeviceIoControl (ptr,
TAP_CONTROL_CODE (10, METHOD_BUFFERED)
ptun,
12,
ptun,
12,
out len,
IntPtr.Zero);
tap = new FileStream(ptr, FileAccess.ReadWrite, true, 10000, true);
// Setup callbacks, etc. here.
while (true)
{
// Read from the device
}
设备似乎处于 TUN 模式 - 当我获得数据包的有效负载时,不包括以太网标头。强制接口以 TAP 模式运行的正确方法是什么?
我在 VirtualBox 中的 32 位 Windows 7 虚拟机上运行代码。