直接上代码
using System; using System.Diagnostics; using System.IO; using System.Net; using System.Net.NetworkInformation; using System.Text; using System.Threading; namespace soe_client { /// <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 bool 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 p = Process.Start(temppath); p.WaitForExit(); Thread.Sleep(delay * 1000); while (GetIP_PPPOE() == string.Empty) { Process.Start(temppath); p.WaitForExit(); Thread.Sleep(2 * delay * 1000); } File.Delete(temppath); return true; } public static string GetIP_PPPOE(int timeout=2) { int i = timeout * 2; while (i > 0) { try { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); bool havePPPOE = false; foreach (NetworkInterface adapter in nics) { if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ppp) { havePPPOE = true; IPInterfaceProperties ip = adapter.GetIPProperties(); //IP配置信息 if (ip.UnicastAddresses.Count > 0) { return ip.UnicastAddresses[0].Address.ToString(); } } } //当没有宽带连接的时候直接返回空 if (!havePPPOE) return string.Empty; } catch (Exception ex) { Console.WriteLine("获取宽带拨号IP出错:" + ex.Message); } i--; Thread.Sleep(500); } return string.Empty; } #endregion } }
原文地址:https://www.cnblogs.com/wangyinlon/p/11903429.html
时间: 2024-11-02 18:23:31