C# 实现自动ADSL拨号

前言

由于工作原因,需要使电脑长时间保持宽带连接状态,并且有动态拨号更换ip的需求,在网上查阅资料许久,首先找到了这篇博客:
使用C#实现ADSL自动拨号

但是本人在win8 64位的系统上并未成功,后来采用bat去实现这个功能并封装成帮助类


类代码

类代码如下

//---------------------------------------名称:基于bat批处理的ADSL动态拨号帮助类
//---------------------------------------更新时间:2017/10/18
//---------------------------------------作者:献丑
//---------------------------------------CSDN地址:http://blog.csdn.net/qq_26712977

using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;

namespace HttpToolsLib
{
    /// 
    /// ADSL拨号帮助类 用批处理实现
    /// 
    public class ADSLIP
    {
        #region 变量
        /// 
        ///生成的临时批处理文件名称
        /// 
        static String _temppath = "temp.bat";
        public static String temppath
        {
            get { return ADSLIP._temppath; }
            set { ADSLIP._temppath = value; }
        }
        /// 
        /// 字符串拼接用
        /// 
        private static StringBuilder sb = new StringBuilder();
        /// 
        /// 拨号等待 默认15秒
        /// 
        public static int delay = 15;
        #endregion

        #region 方法
        /// 
        /// 开始拨号
        /// 
        /// 宽带连接名称
        /// 宽带连接用户名
        /// 宽带连接密码
        public static void ChangeIp(String ADSL_Name = "宽带连接", String ADSL_UserName = "", String ADSL_PassWord = "")
        {
            sb.Clear();
            sb.AppendLine("@echo off");
            sb.AppendLine("set adslmingzi=" + ADSL_Name);
            sb.AppendLine("set adslzhanghao=" + ADSL_UserName);
            sb.AppendLine("set adslmima=" + ADSL_PassWord);
            sb.AppendLine("@Rasdial %adslmingzi% /disconnect");
            sb.AppendLine("ping 127.0.0.1 -n 2");
            sb.AppendLine("Rasdial %adslmingzi% %adslzhanghao% %adslmima%");
            sb.AppendLine("echo 连接中");
            sb.AppendLine("ping 127.0.0.1 -n 2");
            sb.AppendLine("ipconfig");
            // sb.AppendLine("pause");

            using (StreamWriter sw = new StreamWriter(temppath, false, Encoding.Default))
            {
                sw.Write(sb.ToString());
            }
            Process.Start(temppath);
            System.Threading.Thread.Sleep(delay * 1000);
            while (!HttpMethod.CheckIp(null))
            {
                Process.Start(temppath);
                System.Threading.Thread.Sleep(2 * delay * 1000);
            }
            File.Delete(temppath);
        }
        /// 
        /// 获得本地ip
        /// 
        /// 
        public static String GetIP()
        {
            ///获取本地的IP地址
            string AddressIP = string.Empty;
            //遍历
            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    AddressIP = _IPAddress.ToString();
                }
            }
            return AddressIP;
        }
        #endregion
    }
}


GitHub地址:ADSLIP.cs

帮助类说明

调用方式如下

ADSLIP.ChangeIp("宽带名称","宽带用户名","宽带密码");

此方式会出现控制台界面(由于运行bat),但是会自行关闭

使用DotRas进行宽带拨号

网上找的帮助类—-

    /// 
    /// ADSL拨号帮助类 用DotRas实现
    /// 

    public class RASDisplay
    {
        public static string ADSLName { get;  set; }
        public static string ADSLUserName { get;  set; }
        public static string ADSLPassWord { get;  set; }

        /// 
        /// 创建或更新一个PPPOE连接(指定PPPOE名称)
        /// 
        static void CreateOrUpdatePPPOE(string updatePPPOEname)
        {
            RasDialer dialer = new RasDialer();
            RasPhoneBook allUsersPhoneBook = new RasPhoneBook();
            string path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
            allUsersPhoneBook.Open(path);
            // 如果已经该名称的PPPOE已经存在,则更新这个PPPOE服务器地址
            if (allUsersPhoneBook.Entries.Contains(updatePPPOEname))
            {
                allUsersPhoneBook.Entries[updatePPPOEname].PhoneNumber = " ";
                // 不管当前PPPOE是否连接,服务器地址的更新总能成功,如果正在连接,则需要PPPOE重启后才能起作用
                allUsersPhoneBook.Entries[updatePPPOEname].Update();
            }
            // 创建一个新PPPOE
            else
            {
                string adds = string.Empty;
                ReadOnlyCollection readOnlyCollection = RasDevice.GetDevices();
                RasDevice device = RasDevice.GetDevices().Where(o => o.DeviceType == RasDeviceType.PPPoE).First();
                RasEntry entry = RasEntry.CreateBroadbandEntry(updatePPPOEname, device);    //建立宽带连接Entry
                entry.PhoneNumber = " ";
                allUsersPhoneBook.Entries.Add(entry);
            }
        }

        /// 
        /// 断开 宽带连接
        /// 
        public static void Disconnect()
        {
            ReadOnlyCollection conList = RasConnection.GetActiveConnections();
            foreach (RasConnection con in conList)
            {
                con.HangUp();
            }
        }

        /// 
        /// 宽带连接,成功返回true,失败返回 false
        /// 
        /// 宽带连接名称
        /// 宽带账号
        /// 宽带密码
        /// 
        public static bool Connect(string PPPOEname, string username, string password, ref string msg,int delay = 10000)
        {
            try
            {
                CreateOrUpdatePPPOE(PPPOEname);
                using (RasDialer dialer = new RasDialer())
                {
                    dialer.EntryName = PPPOEname;
                    dialer.AllowUseStoredCredentials = true;
                    dialer.Timeout = 1000;
                    dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
                    dialer.Credentials = new NetworkCredential(username, password);
                    dialer.Dial();
                    return true;
                }
            }
            catch (RasException re)
            {
                msg = re.ErrorCode + " " + re.Message;
                return false;
            }
            finally
            {
                Thread.Sleep(delay);
            }
        }
        /// 
        /// 连接
        /// 
        /// 
        public static bool Connect()
        {
            try
            {
                CreateOrUpdatePPPOE(ADSLName);
                using (RasDialer dialer = new RasDialer())
                {
                    dialer.EntryName = ADSLName;
                    dialer.AllowUseStoredCredentials = true;
                    dialer.Timeout = 1000;
                    dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
                    dialer.Credentials = new NetworkCredential(ADSLUserName, ADSLPassWord);
                    dialer.Dial();
                    return true;
                }
            }
            catch (RasException re)
            {
                Console.WriteLine(re.Message);
                return false;
            }
        }
    }

你可能感兴趣的:(C#)