出處:http://www.cnblogs.com/wuhuacong/archive/2010/09/06/1819612.html
有些場合,爲了避免服務對用戶IP的限制或者爲了用戶的方便,可以通過代碼實現自動化的撥號或者斷網操作,通過DotRAS組件,可以非常方便的實現如ADSL、VPN等撥號以及相關操作,DotRAS組件是專門提供這樣遠程訪問服務的模塊,本文介紹如何通過應用該組件,實現ADSL網絡的撥號、斷網、獲取用戶IP的操作。
DotRAS組件的項目地址是:http://dotras.codeplex.com/
先看看Demo的界面效果
具體的代碼邏輯,是通過列出電話簿裏面的撥號連接,設置是通過賬戶密碼或者默認賬戶設置信息,進行撥號即可,使用DotRas組件,使得在DotNet中操作這些功能非常方便,代碼貼上如下所示:
/// <summary>
/// 測試撥號連接
/// </summary>
private void btnTest_Click(object sender, EventArgs e)
{
try
{
RasDialer dialer = new RasDialer();
dialer.EntryName = "聯通網絡";
dialer.PhoneNumber = " ";
dialer.AllowUseStoredCredentials = true;
dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
dialer.Timeout = 1000;
dialer.Dial();
Thread.Sleep(100);
this.LoadConnections();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
/// <summary>
/// 斷開網絡連接
/// </summary>
private void btnLogout_Click(object sender, EventArgs e)
{
ReadOnlyCollection<RasConnection> conList = RasConnection.GetActiveConnections();
foreach (RasConnection con in conList)
{
con.HangUp();
}
this.LoadConnections();
}
private void Form1_Load(object sender, EventArgs e)
{
this.LoadConnections();
}
/// <summary>
/// 顯示活動的連接
/// </summary>
private void LoadConnections()
{
this.comboBox1.Items.Clear();
this.comboBox1.Items.Add(new ComboBoxItem("請選擇一個鏈接...", null));
foreach (RasConnection connection in RasConnection.GetActiveConnections())
{
this.comboBox1.Items.Add(new ComboBoxItem(connection.EntryName, connection.EntryId));
}
this.comboBox1.SelectedIndex = 0;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
this.GetAddressButton.Enabled = this.comboBox1.SelectedIndex > 0;
}
/// <summary>
/// 獲取IP地址信息
/// </summary>
private void GetAddressButton_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach (RasConnection connection in RasConnection.GetActiveConnections())
{
if (connection.EntryId == (Guid)((ComboBoxItem)this.comboBox1.SelectedItem).Value)
{
RasIPInfo ipAddresses = (RasIPInfo)connection.GetProjectionInfo(RasProjectionType.IP);
if (ipAddresses != null)
{
sb.AppendFormat("ClientIP:{0}\r\n", ipAddresses.IPAddress.ToString());
sb.AppendFormat("ServerIP:{0}\r\n", ipAddresses.ServerIPAddress.ToString());
}
}
sb.AppendLine();
}
MessageBox.Show(sb.ToString());
}
通過以上的代碼,可以非常方便實現寬帶的撥號連接和獲取IP等設置,不過斷網之後,一般的IP還是和原來一樣,這個可能和服務器的緩存有關系,爲了實現撥號後,本地爲不同的IP設置,需要特別的處理才可以。
[轉貼] 利用DotRAS組件,實現ADSL的自動撥號斷網自動化操作
相關文章