示例#1
0
        private static int Open_TUNTAP(IntPtr dev, UInt16 flags, bool persistent)
        {
            var ifr = Marshal.AllocHGlobal(IFR_SIZE); // we need 40 bytes, but we allocate a bit more

            var fd = LibCWrapper.Open("/dev/net/tun", O_RDWR);

            if (fd < 0)
            {
                Console.Error.WriteLine("Could not open /dev/net/tun, error: {0}", Marshal.GetLastWin32Error());
                return(fd);
            }

            var memory = new byte[IFR_SIZE];

            Array.Clear(memory, 0, IFR_SIZE);

            var bytes = BitConverter.GetBytes(flags);

            Array.Copy(bytes, 0, memory, IFNAMSIZ, 2);

            if (dev != IntPtr.Zero)
            {
                var devBytes = Encoding.ASCII.GetBytes(Marshal.PtrToStringAnsi(dev));
                Array.Copy(devBytes, memory, Math.Min(devBytes.Length, IFNAMSIZ));
            }

            Marshal.Copy(memory, 0, ifr, IFR_SIZE);

            int err = 0;

            if ((err = LibCWrapper.Ioctl(fd, TUNSETIFF, ifr)) < 0)
            {
                Console.Error.WriteLine("Could not set TUNSETIFF, error: {0}", Marshal.GetLastWin32Error());
                LibCWrapper.Close(fd);
                return(err);
            }

            if (persistent)
            {
                if ((err = LibCWrapper.Ioctl(fd, TUNSETPERSIST, 1)) < 0)
                {
                    Console.Error.WriteLine("Could not set TUNSETPERSIST, error: {0}", Marshal.GetLastWin32Error());
                    LibCWrapper.Close(fd);
                    return(err);
                }
            }

            LibCWrapper.Strcpy(dev, ifr);

            Marshal.FreeHGlobal(ifr);

            return(fd);
        }
        private static bool DoIoctl(IoctlCode code, IntPtr data)
        {
            int err;

            if ((err = LibCWrapper.Ioctl(fd, (int)code, data)) < 0)
            {
                var lastErrorCode    = Marshal.GetLastWin32Error();
                var lastErrorMessage = LibCWrapper.Strerror(lastErrorCode);

                loggingParent.Log(LogLevel.Error, "There was an error when executing the {0} ioctl: {1} (0x{2:X})", Enum.GetName(typeof(IoctlCode), code), lastErrorMessage, lastErrorCode);
                LibCWrapper.Close(fd);
                return(false);
            }

            return(true);
        }