Placing a TAP-Windows device in TAP mode

1

I am using TAP-Windows (from the OpenVPN project) to create an interface as described here and here. I am basing my code of the example provided in the first article:

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
}

It seems that the device is in TUN mode - while I get the payload of the packets, the ethernet headers are not included. What is the correct way to force the interface to operate in TAP mode?

I am running the code on a 32 bit Windows 7 virtual machine in VirtualBox.

c#
windows
network-programming
tun
asked on Stack Overflow Jan 22, 2014 by Johan_B

1 Answer

3

I'm working with this example just now. I realize that when you make this call:

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

it's when the interface is placed in TUN mode. What I did was just to ignore this (I did't make this call to DeviceIoControl), and then all packets where received by the File Stream.

answered on Stack Overflow Mar 1, 2014 by Adrián Rivero • edited Nov 28, 2018 by Adrián Rivero

User contributions licensed under CC BY-SA 3.0