Пример #1
0
        /// <summary>
        ///     搜索出口和TUNTAP适配器
        /// </summary>
        public static bool SearchTapAdapter()
        {
            Global.TUNTAP.Adapter     = null;
            Global.TUNTAP.Index       = -1;
            Global.TUNTAP.ComponentID = TUNTAP.GetComponentID();

            // 搜索 TUN/TAP 适配器的索引
            if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID))
            {
                Logging.Info("TAP 适配器未安装");
                return(false);
            }

            // 根据 ComponentID 寻找 Tap适配器
            try
            {
                var adapter = NetworkInterface.GetAllNetworkInterfaces().First(_ => _.Id == Global.TUNTAP.ComponentID);
                Global.TUNTAP.Adapter = adapter;
                Global.TUNTAP.Index   = adapter.GetIPProperties().GetIPv4Properties().Index;
                Logging.Info(
                    $"TAP 适配器:{adapter.Name} {adapter.Id} {adapter.Description}, index: {Global.TUNTAP.Index}");
                return(true);
            }
            catch (Exception e)
            {
                var msg = e switch
                {
                    InvalidOperationException _ => $"找不到标识符为 {Global.TUNTAP.ComponentID} 的 TAP 适配器: {e.Message}",
                    NetworkInformationException _ => $"获取 Tap 适配器信息错误: {e.Message}",
                    _ => $"Tap 适配器其他异常: {e}"
                };
                Logging.Error(msg);
                return(false);
            }
        }
Пример #2
0
        public static bool IsEqual(this NetworkInformationException @this, NetworkInformationException other)
        {
            // NetworkInformationException has a different StackTrace and HResult on Unix and OSX.

            return(@this != null &&
                   other != null &&
                   @this.Data.CheckSequenceEquals(other.Data) &&
                   // @this.Message == other.Message &&    // Message is platform dependent, as it is generated by the platform from the error code
                   @this.Source == other.Source &&
                   @this.HelpLink == other.HelpLink &&
                   CheckEquals(@this.InnerException, other.InnerException));
        }
Пример #3
0
        public void Interfaces_ShouldLog_ExpectedException()
        {
            // Arrange
            var exception = new NetworkInformationException();

            _origin.Interfaces().Throws(exception);
            var subject = new SafeSystemNetworkInterfaces(_logger, _origin);

            // Act
            _ = subject.Interfaces();
            // Assert
            _logger.ReceivedWithAnyArgs().Error("");
        }
        public void TestNetworkInformationException()
        {
            var value = new NetworkInformationException(12345);

            try
            {
                ExceptionDispatchInfo.Capture(value).Throw();
            }
            catch (NetworkInformationException ex)
            {
                Assert.That(ex, Is.Not.SameAs(value));
                Assert.That(ex.ErrorCode, Is.EqualTo(value.ErrorCode));
            }
        }
Пример #5
0
        /// <summary>
        ///     搜索出口和TUNTAP适配器
        /// </summary>
        public static bool SearchTapAdapter()
        {
            // 搜索 TUN/TAP 适配器的索引
            if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID = TUNTAP.GetComponentID()))
            {
                Logging.Info("找不到 TAP 适配器");
                if (MessageBoxX.Show(i18N.Translate("TUN/TAP driver is not detected. Is it installed now?"),
                                     confirm: true) == DialogResult.OK)
                {
                    Configuration.addtap();
                    // 给点时间,不然立马安装完毕就查找适配器可能会导致找不到适配器ID
                    Thread.Sleep(1000);
                    if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID = TUNTAP.GetComponentID()))
                    {
                        Logging.Error("找不到 TAP 适配器,驱动可能安装失败");
                        return(false);
                    }
                }
                else
                {
                    Logging.Info("取消安装 TAP 驱动 ");
                    return(false);
                }
            }

            // 根据 ComponentID 寻找 Tap适配器
            try
            {
                var adapter = NetworkInterface.GetAllNetworkInterfaces().First(_ => _.Id == Global.TUNTAP.ComponentID);
                Global.TUNTAP.Adapter = adapter;
                Global.TUNTAP.Index   = adapter.GetIPProperties().GetIPv4Properties().Index;
                Logging.Info(
                    $"TAP 适配器:{adapter.Name} {adapter.Id} {adapter.Description}, index: {Global.TUNTAP.Index}");
            }
            catch (Exception e)
            {
                var msg = e switch
                {
                    InvalidOperationException _ => $"找不到标识符为 {Global.TUNTAP.ComponentID} 的 TAP 适配器: {e.Message}",
                    NetworkInformationException _ => $"获取 Tap 适配器信息错误: {e.Message}",
                    _ => $"Tap 适配器其他异常: {e}"
                };
                Logging.Error(msg);
                return(false);
            }

            return(true);
        }
Пример #6
0
        /// <summary>
        ///     搜索出口和TUNTAP适配器
        /// </summary>
        public static bool SearchTapAdapter()
        {
            // 搜索 TUN/TAP 适配器的索引
            if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID = TUNTAP.GetComponentID()))
            {
                Logging.Info("TAP adapter not found");
                if (MessageBoxX.Show(i18N.Translate("TUN/TAP driver is not detected. Is it installed now?"),
                                     confirm: true) == DialogResult.OK)
                {
                    TUNTAP.addtap();
                    // 给点时间,不然立马安装完毕就查找适配器可能会导致找不到适配器ID
                    Thread.Sleep(1000);
                    if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID = TUNTAP.GetComponentID()))
                    {
                        Logging.Error("TAP adapter not found, The driver may fail to install");
                        return(false);
                    }
                }
                else
                {
                    Logging.Info("TAP driver installation cancelled");
                    return(false);
                }
            }

            // 根据 ComponentID 寻找 Tap适配器
            try {
                var adapter = NetworkInterface.GetAllNetworkInterfaces().First(_ => _.Id == Global.TUNTAP.ComponentID);
                Global.TUNTAP.Adapter = adapter;
                Global.TUNTAP.Index   = adapter.GetIPProperties().GetIPv4Properties().Index;
                Logging.Info(
                    $"TAP adapter: {adapter.Name} {adapter.Id} {adapter.Description}, index: {Global.TUNTAP.Index}");
            } catch (Exception e) {
                var msg = e switch
                {
                    InvalidOperationException _ => $"Could not find tap adapter with identifier {Global.TUNTAP.ComponentID}: {e.Message}",
                    NetworkInformationException _ => $"Error getting tap adapter information: {e.Message}",
                    _ => $"Tap adapter other exceptions: {e}"
                };
                Logging.Error(msg);
                return(false);
            }

            return(true);
        }
        private void Setup(StartIPOptions startIPOptions)
        {
            int num;

            if (Socket.OSSupportsIPv4 && ((startIPOptions & StartIPOptions.StartIPv4) != StartIPOptions.None))
            {
                if (UnsafeNclNativeMethods.OSSOCK.WSAIoctl_Blocking(this.ipv4Socket.DangerousGetHandle(), 0x28000017, null, 0, null, 0, out num, SafeNativeOverlapped.Zero, IntPtr.Zero) != SocketError.Success)
                {
                    NetworkInformationException exception = new NetworkInformationException();
                    if (exception.ErrorCode != 0x2733L)
                    {
                        this.Dispose();
                        return;
                    }
                }
                if (UnsafeNclNativeMethods.OSSOCK.WSAEventSelect(this.ipv4Socket, this.ipv4Socket.GetEventHandle().SafeWaitHandle, AsyncEventBits.FdAddressListChange) != SocketError.Success)
                {
                    this.Dispose();
                    return;
                }
            }
            if (Socket.OSSupportsIPv6 && ((startIPOptions & StartIPOptions.StartIPv6) != StartIPOptions.None))
            {
                if (UnsafeNclNativeMethods.OSSOCK.WSAIoctl_Blocking(this.ipv6Socket.DangerousGetHandle(), 0x28000017, null, 0, null, 0, out num, SafeNativeOverlapped.Zero, IntPtr.Zero) != SocketError.Success)
                {
                    NetworkInformationException exception2 = new NetworkInformationException();
                    if (exception2.ErrorCode != 0x2733L)
                    {
                        this.Dispose();
                        return;
                    }
                }
                if (UnsafeNclNativeMethods.OSSOCK.WSAEventSelect(this.ipv6Socket, this.ipv6Socket.GetEventHandle().SafeWaitHandle, AsyncEventBits.FdAddressListChange) != SocketError.Success)
                {
                    this.Dispose();
                }
            }
        }
Пример #8
0
        /// <summary>
        ///     搜索出口和TUNTAP适配器
        /// </summary>
        private static bool SearchAdapters()
        {
            // 寻找出口适配器
            if (Win32Native.GetBestRoute(BitConverter.ToUInt32(IPAddress.Parse("114.114.114.114").GetAddressBytes(), 0), 0, out var pRoute) != 0)
            {
                Logging.Error("GetBestRoute 搜索失败(找不到出口适配器)");
                return(false);
            }

            Global.Adapter.Index = pRoute.dwForwardIfIndex;

            // 搜索 TUN/TAP 适配器的索引
            if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID = TUNTAP.GetComponentID()))
            {
                Logging.Info("找不到 TAP 适配器");
                if (MessageBoxX.Show(i18N.Translate("TUN/TAP driver is not detected. Is it installed now?"), confirm: true) == DialogResult.OK)
                {
                    Configuration.addtap();
                    // 给点时间,不然立马安装完毕就查找适配器可能会导致找不到适配器ID
                    Thread.Sleep(1000);
                    if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID = TUNTAP.GetComponentID()))
                    {
                        Logging.Error("找不到 TAP 适配器,驱动可能安装失败");
                        return(false);
                    }
                }
                else
                {
                    Logging.Info("取消安装 TAP 驱动 ");
                    return(false);
                }
            }

            // 根据 IP Index 寻找 出口适配器
            var errorAdaptersId = new List <string>();

            try
            {
                var adapter = NetworkInterface.GetAllNetworkInterfaces().First(_ =>
                {
                    try
                    {
                        return(_.GetIPProperties().GetIPv4Properties().Index == Global.Adapter.Index);
                    }
                    catch (NetworkInformationException)
                    {
                        errorAdaptersId.Add(_.Id);
                        return(false);
                    }
                });
                Global.Adapter.Address = adapter.GetIPProperties().UnicastAddresses.First(ip => ip.Address.AddressFamily == AddressFamily.InterNetwork).Address;
                Global.Adapter.Gateway = new IPAddress(pRoute.dwForwardNextHop);
                Logging.Info($"出口 IPv4 地址:{Global.Adapter.Address}");
                Logging.Info($"出口 网关 地址:{Global.Adapter.Gateway}");
                Logging.Info($"出口适配器:{adapter.Name} {adapter.Id} {adapter.Description}, index: {Global.Adapter.Index}");
            }
            catch (Exception e)
            {
                Logging.Error($"找不到 IP Index 为 {Global.Adapter.Index} 的出口适配器: {e.Message}");
                PrintAdapters();
                return(false);
            }

            // 根据 ComponentID 寻找 Tap适配器
            try
            {
                var adapter = NetworkInterface.GetAllNetworkInterfaces().First(_ => _.Id == Global.TUNTAP.ComponentID);
                Global.TUNTAP.Adapter = adapter;
                Global.TUNTAP.Index   = adapter.GetIPProperties().GetIPv4Properties().Index;
                Logging.Info($"TAP 适配器:{adapter.Name} {adapter.Id} {adapter.Description}, index: {Global.TUNTAP.Index}");
            }
            catch (Exception e)
            {
                var msg = e switch
                {
                    InvalidOperationException _ => $"找不到标识符为 {Global.TUNTAP.ComponentID} 的 TAP 适配器: {e.Message}",
                    NetworkInformationException _ => $"获取 Tap 适配器信息错误: {e.Message}",
                    _ => $"Tap 适配器其他异常: {e}"
                };
                Logging.Error(msg);
                PrintAdapters();
                return(false);
            }

            return(true);

            void PrintAdapters()
            {
                Logging.Info("所有适配器:\n" +
                             NetworkInterface.GetAllNetworkInterfaces().Aggregate(string.Empty, (current, adapter)
                                                                                  => current + $"{ /*如果加了 ’*‘ 代表遍历中出现异常的适配器  */(errorAdaptersId.Contains(adapter.Id) ? "*" : "")}{adapter.Name} {adapter.Id} {adapter.Description}{Global.EOF}"));
            }
        }
Пример #9
0
 public WrapperNetworkInformationException(NetworkInformationException inner)
     : base(inner.ErrorCode)
 {
     this._innerStackTrace = inner.StackTrace;
 }
Пример #10
0
        private unsafe void Setup(StartIPOptions startIPOptions)
        {
            int length;
            SocketError errorCode;

            if (Socket.SupportsIPv4 && (startIPOptions & StartIPOptions.StartIPv4) != 0){
                errorCode = (SocketError)UnsafeNclNativeMethods.OSSOCK.WSAIoctl_Blocking(
                    ipv4Socket.DangerousGetHandle(),
                    (int) IOControlCode.AddressListChange,
                    null, 0, null, 0,
                    out length,
                    IntPtr.Zero, IntPtr.Zero);

                if (errorCode != SocketError.Success) {
                    NetworkInformationException exception = new NetworkInformationException();
                    if (exception.ErrorCode != (uint)SocketError.WouldBlock) {
                        Dispose();
                        return;
                    }
                }

                errorCode = (SocketError)UnsafeNclNativeMethods.OSSOCK.WSAEventSelect(ipv4Socket, ipv4Socket.GetEventHandle().SafeWaitHandle, AsyncEventBits.FdAddressListChange);
                if (errorCode != SocketError.Success) {
                    Dispose();
                    return;
                }
            }

            if(Socket.OSSupportsIPv6 && (startIPOptions & StartIPOptions.StartIPv6) !=0){
                errorCode = (SocketError) UnsafeNclNativeMethods.OSSOCK.WSAIoctl_Blocking(
                    ipv6Socket.DangerousGetHandle(),
                    (int) IOControlCode.AddressListChange,
                    null, 0, null, 0,
                    out length,
                    IntPtr.Zero, IntPtr.Zero);

                if (errorCode != SocketError.Success) {
                    NetworkInformationException exception = new NetworkInformationException();
                    if (exception.ErrorCode != (uint)SocketError.WouldBlock) {
                        Dispose();
                        return;
                    }
                }

                errorCode = (SocketError)UnsafeNclNativeMethods.OSSOCK.WSAEventSelect(ipv6Socket, ipv6Socket.GetEventHandle().SafeWaitHandle, AsyncEventBits.FdAddressListChange);
                if (errorCode != SocketError.Success) {
                    Dispose();
                    return;
                }
            }
        }