C# 实现自动ADSL拨号

C# 专栏收录该内容
18 篇文章 0 订阅

前言

由于工作原因,需要使电脑长时间保持宽带连接状态,并且有动态拨号更换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;
            }
        }
    }
  • 1
    点赞
  • 2
    评论
  • 1
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

Cubeeeeee

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值