`
380071587
  • 浏览: 480036 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

vpn 连接

    博客分类:
  • vpn
vpn 
阅读更多
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace VPN
{
    /// <summary>
    /// Class to maintain connectivity to a specific VPN connection
    /// </summary>
    /// <history>
    ///     [Tim Hibbard]   01/24/2007 Created
    /// </history>
    public class VPNS
    {
        #region --Const--
        /// <summary>
        /// Where the rasphone.exe lives
        /// </summary>
        private const string VPNPROCESS = "C:\\WINDOWS\\system32\\rasphone.exe";
        #endregion

        #region --Fields--
        /// <summary>
        /// Internal variable for VPNConnectionName
        /// </summary>
        private string _VPNConnectionName = "";
        /// <summary>
        /// Internal variable for IPToPing
        /// </summary>
        private string _IPToPing = "";
        /// <summary>
        /// Internal variable for IsConnected
        /// </summary>
        private bool _isConnected = false;
        /// <summary>
        /// Timer that manages the Manage function
        /// </summary>
        private System.Timers.Timer MonitorTimer;
        /// <summary>
        /// Bool to flag if the system is currently checking for network validity
        /// </summary>
        private bool _isChecking = false;
        /// <summary>
        /// Bool to flag if the system is currently in a Manage loop
        /// </summary>
        private bool _isManaging = false;
        #endregion

        #region --Events--
        public delegate void PingingHandler();
        public delegate void ConnectingHandler();
        public delegate void DisconnectingHandler();
        public delegate void IdleHandler();
        public delegate void ConnectionStatusChangedHandler(bool Connected);

        /// <summary>
        /// Fires when validating connectivity
        /// </summary>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        public event PingingHandler Pinging;

        /// <summary>
        /// Fired when it is trying to connect to the VPN
        /// </summary>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        public event ConnectingHandler Connecting;

        /// <summary>
        /// Fired when it is trying to disconnect from the VPN
        /// </summary>
        public event DisconnectingHandler Disconnecting;

        /// <summary>
        /// Fired when it is done working for the moment
        /// </summary>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        public event IdleHandler Idle;

        /// <summary>
        /// Fired when the IsConnected Property changes
        /// </summary>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        public event ConnectionStatusChangedHandler ConnectionStatusChanged;

        /// <summary>
        /// Call to raise Pinging event
        /// </summary>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        protected void OnPinging()
        {
            if (Pinging != null)
            {
                Pinging();
            }
        }

        /// <summary>
        /// Call to raise Connecting event
        /// </summary>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        protected void OnConnecting()
        {
            if (Connecting != null)
            {
                Connecting();
            }
        }

        /// <summary>
        /// Call to raise Disconnecting event
        /// </summary>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        protected void OnDisconnecting()
        {
            if (Disconnecting != null)
            {
                Disconnecting();
            }
        }

        /// <summary>
        /// Call to raise Idle event
        /// </summary>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        protected void OnIdle()
        {
            if (Idle != null)
            {
                Idle();
            }
        }

        /// <summary>
        /// Call to raise ConnectionStatusChanged event
        /// </summary>
        /// <param name="Connected">If connected to network</param>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        protected void OnConnectionStatusChanged(bool Connected)
        {
            if (ConnectionStatusChanged != null)
            {
                ConnectionStatusChanged(Connected);
            }
        }

        #endregion

        #region --Properties--
        /// <summary>
        /// Returns if you are connected to the network
        /// </summary>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        public bool IsConnected
        {
            get { return _isConnected; }
        }

        /// <summary>
        /// IP to ping to validate connectivity
        /// </summary>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        public string IPToPing
        {
            get { return _IPToPing; }
            set { _IPToPing = value; }
        }

        /// <summary>
        /// Name of VPN connection as seen in network connections (not case sensitive)
        /// </summary>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        public string VPNConnectionName
        {
            get { return _VPNConnectionName; }
            set { _VPNConnectionName = value; }
        }
        #endregion

        #region --Private Methods--
        /// <summary>
        /// Pings the provided IP to validate connection
        /// </summary>
        /// <returns>True if you are connected</returns>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        public bool TestConnection()
        {
            bool RV = false;
            _isChecking = true;
            try
            {
                OnPinging();
                System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();

                if (ping.Send(_IPToPing).Status == System.Net.NetworkInformation.IPStatus.Success)
                {
                    RV = true;
                }
                else
                {
                    RV = false;
                }
                ping = null;
                if (RV != _isConnected)
                {
                    _isConnected = RV;
                    OnConnectionStatusChanged(_isConnected);
                }
                OnIdle();
            }
            catch (Exception Ex)
            {
                Debug.Assert(false, Ex.ToString());
                RV = false;
                OnIdle();
            }
            _isChecking = false;
            return RV;
        }

        /// <summary>
        /// Shells the command to connect to the VPN
        /// </summary>
        /// <returns>True if connected</returns>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        private bool ConnectToVPN()
        {
            bool RV = false;
            try
            {
                OnConnecting();
                Process.Start(VPNPROCESS, " -d " + _VPNConnectionName);
                System.Windows.Forms.Application.DoEvents();
                System.Threading.Thread.Sleep(5000);
                System.Windows.Forms.Application.DoEvents();
                RV = true;
                OnIdle();

            }
            catch (Exception Ex)
            {
                Debug.Assert(false, Ex.ToString());
                RV = false;
                OnIdle();
            }
            return RV;
        }

        /// <summary>
        /// Shells the command to disconnect from the VPN connection
        /// </summary>
        /// <returns>True if successfully disconnected</returns>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        private bool DisconnectFromVPN()
        {
            bool RV = false;
            try
            {
                OnDisconnecting();
                System.Diagnostics.Process.Start(VPNPROCESS, " -h " + _VPNConnectionName);
                System.Windows.Forms.Application.DoEvents();
                System.Threading.Thread.Sleep(8000);
                System.Windows.Forms.Application.DoEvents();
                RV = true;
                OnIdle();
            }
            catch (Exception Ex)
            {
                Debug.Assert(false, Ex.ToString());
                RV = false;
                OnIdle();
            }
            return RV;
        }

        /// <summary>
        /// Handles the grunt work.
        /// </summary>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        private void Manage()
        {
            try
            {
                if (!_isManaging)
                {
                    _isManaging = true;
                    if (!_isChecking)
                    {
                        if (!TestConnection())
                        {
                            ConnectToVPN();
                            if (!TestConnection())
                            {
                                DisconnectFromVPN();
                                ConnectToVPN();
                                if (!TestConnection())
                                {
                                    DisconnectFromVPN();
                                    ConnectToVPN();
                                }
                            }
                        }
                    }
                    _isManaging = false;
                }
            }
            catch (Exception)
            {
                _isManaging = false;
            }
        }
        #endregion

        #region --Public Methods--
        /// <summary>
        /// Overloaded end point to begin monitoring VPN status
        /// </summary>
        /// <param name="VPNName">Name of VPN connection as seen in network connections (not case sensitive)</param>
        /// <param name="IPtoPing">IP to ping to validate connectivity</param>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        public void StartManaging(string VPNName, string IPtoPing)
        {
            _VPNConnectionName = VPNName;
            _IPToPing = IPtoPing;
            StartManaging();

        }

        /// <summary>
        /// End point to begin monitoring VPN status
        /// </summary>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        public void StartManaging()
        {
            if (!string.IsNullOrEmpty(_VPNConnectionName) & !string.IsNullOrEmpty(_IPToPing))
            {
                MonitorTimer = new System.Timers.Timer(15000);
                MonitorTimer.Enabled = true;
                MonitorTimer.Elapsed += new System.Timers.ElapsedEventHandler(MonitorTimer_Elapsed);
                System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged += new System.Net.NetworkInformation.NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
                Microsoft.Win32.SystemEvents.PowerModeChanged += new Microsoft.Win32.PowerModeChangedEventHandler(SystemEvents_PowerModeChanged);
                Manage();
            }
        }
        #endregion

        #region --Constructors--
        /// <summary>
        /// Overloaded constructor
        /// </summary>
        /// <param name="VPNName">Name of VPN connection as seen in network connections (not case sensitive)</param>
        /// <param name="IPtoPing">IP to ping to validate connectivity</param>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        public VPNS(string VPNName, string IPtoPing)
        {
            StartManaging(VPNName, IPtoPing);
        }

        /// <summary>
        /// Default empty constructor
        /// </summary>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        public VPNS()
        {
        }
        #endregion

        #region --Event Handlers--
        /// <summary>
        /// Handles the event that is raised when the computer goes into, or comes out of, standby. Very useful for laptops
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
        {
            if (e.Mode == Microsoft.Win32.PowerModes.Resume)
            {
                MonitorTimer.Stop();
                System.Threading.Thread.Sleep(15000);
                MonitorTimer.Start();
            }
            if (e.Mode == Microsoft.Win32.PowerModes.Suspend)
            {
                MonitorTimer.Stop();
            }
        }

        /// <summary>
        /// Handles the event that is raised when the network status changes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        void NetworkChange_NetworkAvailabilityChanged(object sender, System.Net.NetworkInformation.NetworkAvailabilityEventArgs e)
        {
            if (e.IsAvailable)
            {
                if (!MonitorTimer.Enabled)
                {
                    MonitorTimer.Start();
                }
            }
            else
            {
                MonitorTimer.Stop();
            }
        }

        /// <summary>
        /// Handles the event the timer raises when it elapses
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <history>
        ///     [Tim Hibbard]   01/24/2007 Created
        /// </history>
        void MonitorTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Manage();
        }
        #endregion
    }
}

 

分享到:
评论

相关推荐

    路由器怎么设置vpn连接.doc

    路由器怎么设置vpn连接.doc

    Win10系统—VPN连接无法启动虚拟网卡任务.pdf

    Win10系统—VPN连接无法启动虚拟网卡任务.pdf

    win10系统vpn连接720错误怎么办?.docx

    win10系统vpn连接720错误怎么办?.docx

    win10系统vpn连接720错误怎么办?_1.docx

    win10系统vpn连接720错误怎么办?_1.docx

    学生考勤管理系统课程设计C++.rar

    C++ 学生考勤管理系统 课程名称:C++程序设计课程设计 设计题目:学生考勤管理系统 已知技术参数和设计要求: ...在学生考勤管理系统中,考勤信息记录了学生的缺课情况,它包括:缺课日期、第几节课、课程名称、...

    Remote Desktop Manager Enterprise远程桌面连接工具.rar

    此外 Remote Desktop Manager 还支持保存多个远程桌面连接、多个ftp连接和vpn连接,最大程度的为用户提供高效率的服务器管理能力,更有利于IT维护人员对日益增多的服务器的集中控制,remotedesktop使用非常简单,...

    雅马哈路由器配置大全.docx

    雅马哈路由器配置大全 雅马哈路由器 设置说明手册 ... 远程VPN连接 23 8.1 PPTP-VPN 23 8.2 L2TP/IPsec VPN 25 8.3PPTP和L2TP/IPsec VPN并用 28 9. 连接3G等移动通信网络 31 10. 其它 32 10.1. netvolante dns (dynam

    WIN7下L2TP拨号

    这样描述了在WIN7系统下进行L2TP拨号上网的方法。

    工业路由器和民用路由器的区别.pdf

    安全性差异 工业级路由器要多很多安全规则设定和更高级的防火墙,如支持 APN/VPDN 专网,同时 设备具有 IPSEC、PPTP、L2TP、GRE、OPENVPN 多种 VPN 连接, 具有 VPN 客户端、服务端等 功能而。民用路由甚至有些都...

    远程桌面管理工具 Devolutions Remote Desktop Manager 2020.1.14.0 中文多语免费版.zip

    支持 VPN 连接,双显示器,等等。该软件兼容兼容 Microsoft Remote Desktop,终端服务,VNC,LogMeIn,Team Viewer,FTP,SSH,Telnet,Dameware,X Window,VMware,Virtual PC,PC Anywhere, Hyper-V, Citrix, ...

    AWS混合网络设计架构模式.pptx

    它作为一个集中式路由器,可以连接到多个Direct Connect和AWS VPN连接,简化了网络架构的复杂性。Transit Gateway的路由表允许用户定义和传播路由,确保流量按照预期路径流动。例如,通过Attachment(连接)和路由表...

    NetExtender

    5. 输入SonicWALL防火墙的地址和凭据,建立SSL VPN连接。 总的来说,NetExtender 是一个强大的远程访问解决方案,尤其对于跨国企业或在日本有业务的公司来说,日文新版可以提供更加友好的用户体验和符合当地法规的...

    【精品】xx智慧教育云平台-总体建设方案V1.095页).doc

    教育城域网信息中心分别高速连接到互联网和市教育网,教育局的所属学校通过VPN连接,建成统一规划和统一管理的网络平台。充分利用网络技术,建立了学校——教育局之间的沟通桥梁,从而避免了信息孤岛的产生。

    在RedHat系的Linux中使用nmcli命令管理网络的教程.docx

    针对这些网络类型,NetworkManager 可以配置他们的网络别名,IP 地址,静态路由,DNS,VPN 连接以及很多其它的特殊参数。 nmcli 命令的基本语法是 `nmcli [OPTIONS] OBJECT {COMMAND | help}`。我们可以通过 TAB 键...

    EasyConnectInstaller+MobaXterm安装包.rar

    标题 "EasyConnectInstaller+Moba...总结来说,这个压缩包提供了一种便捷的方式,让用户同时获取到用于SSL VPN连接的EasyConnect和强大SSH客户端MobaXterm的安装程序,从而能够安全、高效地进行远程服务器管理和操作。

    Cisco路由器配置实例

    第一章 路由器配置基础 一、基本设置...二、交换机间链路(ISL)协议 三、虚拟局域网(VLAN)路由实例 附录一:Cisco路由器口令恢复 附录二:IP地址分配 附录三:Cisco 路由配置语句汇总 附录四:Cisco VPN连接配置实例

    Stas'M 的 Windows XP 终端服务实时补丁_Pascal_代码_下载

    Stas'M 的终端服务实时补丁允许您在 Windows XP 机器上修补远程...保持活动 VPN 连接(例如 PPTP 或 PPPoE) 每个用户一个或多个会话 启用或禁用远程登录时的空白密码 更多详情、使用方法,请下载后阅读README.md文件

    知网下载文献的方法.txt

    使用VPN或学校资源:部分师生可以通过VPN连接校园网来访问和下载知网资源。另外,图书馆资源也是一个很好的途径,特别是省级图书馆,如浙江图书馆等,它们通常与知网有合作关系,可以提供免费的下载服务。 利用第...

    基于 openfortivpn 连接到Fortigate- Hardware的 VPN-GUI_C++_代码_下载

    开放式 基于 openfortivpn 连接到 Fortigate-Hardware 的 VPN-GUI 更多详情、使用方法,请下载后阅读README.md文件

    MAC版 easyConnect_7_6_7_4

    1. **SSL VPN连接**:EasyConnect基于SSL(Secure Socket Layer)协议,提供安全的虚拟私有网络连接,数据传输过程被加密,保护用户数据免受窃听和篡改。 2. **多平台支持**:除了MAC版,EasyConnect还支持Windows...

Global site tag (gtag.js) - Google Analytics