将TAP-Windows设备置于TAP模式

时间:2014-01-22 07:06:35

标签: c# windows network-programming tun

我正在使用TAP-Windows(来自OpenVPN项目)创建一个如herehere所述的界面。我基于第一篇文章中提供的示例代码:

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虚拟机上运行代码。

1 个答案:

答案 0 :(得分:3)

我刚才正在使用这个例子。我意识到,当你打这个电话时:

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);

当接口处于TUN模式时。我所做的只是忽略了这一点(我没有调用DeviceIoControl),然后是文件流接收到的所有数据包。