C# 实现自动ADSL拨号

C# 实现自动ADSL拨号前言由于工作原因,需要使电脑长时间保持宽带连接状态,并且有动态拨号更换ip的需求,在网上查阅资料许久,首先找到了这篇博客:使用C#实现ADSL自动拨号但是本人在win864位的系统上并未成功,后来采用bat去实现这个功能并封装成帮助类类代码类代码如下//-名称:基于bat批处理的ADS…

C#

前言

由于工作原因,需要使电脑长时间保持宽带连接状态,并且有动态拨号更换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
{
    /// <summary>
    /// ADSL拨号帮助类 用批处理实现
    /// </summary>
    public class ADSLIP
    {
        #region 变量
        /// <summary>
        ///生成的临时批处理文件名称
        /// </summary>
        static String _temppath = "temp.bat";
        public static String temppath
        {
            get { return ADSLIP._temppath; }
            set { ADSLIP._temppath = value; }
        }
        /// <summary>
        /// 字符串拼接用
        /// </summary>
        private static StringBuilder sb = new StringBuilder();
        /// <summary>
        /// 拨号等待 默认15秒
        /// </summary>
        public static int delay = 15;
        #endregion

        #region 方法
        /// <summary>
        /// 开始拨号
        /// </summary>
        /// <param name="ADSL_Name">宽带连接名称</param>
        /// <param name="ADSL_UserName">宽带连接用户名</param>
        /// <param name="ADSL_PassWord">宽带连接密码</param>
        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);
        }
        /// <summary>
        /// 获得本地ip
        /// </summary>
        /// <returns></returns>
        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进行宽带拨号

网上找的帮助类—-

    /// <summary>
    /// ADSL拨号帮助类 用DotRas实现
    /// </summary>

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

        /// <summary>
        /// 创建或更新一个PPPOE连接(指定PPPOE名称)
        /// </summary>
        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<RasDevice> 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);
            }
        }

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

        /// <summary>
        /// 宽带连接,成功返回true,失败返回 false
        /// </summary>
        /// <param name="PPPOEname">宽带连接名称</param>
        /// <param name="username">宽带账号</param>
        /// <param name="password">宽带密码</param>
        /// <returns></returns>
        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);
            }
        }
        /// <summary>
        /// 连接
        /// </summary>
        /// <returns></returns>
        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# 实现自动ADSL拨号分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/33892.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注