目前大部分家庭的上网方式都是基于PPPoE协议的,它是动态分配IP地址,以弥补IPv4地址短缺的问题(好期待IPv6啊,到时候把我家的每根筷子上都分配一个IP)。由于有时候需要切换IP地址,但是到路由的设置界面里切换比较麻烦,因此自己做了个小软件,这样就方便多了。我的路由是D-Link 504,大家根据自己的情况改动一下地址。
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; namespace ChangeIP { class Program { static void Main(string[] args) { //获取当前IP string result = GetHttpWeb("http://192.168.0.1/info.htm"); int start = result.IndexOf("wanIP"); int end = result.IndexOf("subMask"); result = result.Substring(start, end - start); Console.Write(result); //通过路由切换IP GetHttpWeb("http://192.168.0.1/do_cmd.htm?CMD=WAN_CON&GO=info.htm&action=4"); //显示进度 char[] progress ={ '|', '/', '-', '\\' }; for (int i = 0; i < 10; i++) { Console.Write("Changing " + progress[i % 4]); Console.Write('\r'); System.Threading.Thread.Sleep(500); } Console.WriteLine(); //显示新的IP result = GetHttpWeb("http://192.168.0.1/info.htm"); start = result.IndexOf("wanIP"); end = result.IndexOf("subMask"); result = result.Substring(start, end - start); Console.Write(result); Console.ReadKey(true); } //读取网页 public static string GetHttpWeb(string uri) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.Credentials = new NetworkCredential("admin", "");//路由的用户名和密码 request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6"; // Get the response. HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); } catch (Exception) { throw; } // Get the stream containing content returned by the server. Stream dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream, Encoding.GetEncoding("GB2312")); // Read the content. string rsp = reader.ReadToEnd(); // Cleanup the streams and the response. reader.Close(); dataStream.Close(); response.Close(); request.Abort(); return rsp; } } }