给梦一个奔跑的方向!
PDF Print E-mail
User Rating: / 0
PoorBest 
Written by xlingfairy
Tuesday, 02 March 2010 14:48
1, 新建一个VPN,
在DotRas.RasPhoneBook 里,是以VPN连接名称标识不同的连接的。如果以存在这个名字,就不能新建,只能更新。建立成功后,在网络连接的虚拟专用网络里会出现一个新的VPN连接。
 
。。。
private static RasVpnStrategy rasstart = RasVpnStrategy.L2tpFirst;
private static RasPhoneBook pb = new RasPhoneBook();
private static readonly string VPNNAME = "VPN1";
。。。
pb.Open();
。。。
private static void CreateOrUpdateVPNEntry( string ip, string user, string pwd ) {
    RasEntry entry;
    if (!pb.Entries.Contains(VPNNAME)) {
        entry = RasEntry.CreateVpnEntry(VPNNAME, ip, rasstart, RasDevice.GetDeviceByName("(L2TP)", RasDeviceType.Vpn));
        pb.Entries.Add(entry);
    } else {
        entry = pb.Entries[VPNNAME];
        entry.PhoneNumber = ip;
        IPAddress _ip;
        IPAddress.TryParse(ip, out _ip);
        entry.IPAddress = _ip;
    }
    NetworkCredential nc = new NetworkCredential(user,pwd);
    entry.UpdateCredentials(nc);
    entry.Update();
}
 
这里我指定的是L2TP,还有另外一种选择:PPTP,但是我不了解这两种方式的区别,这里有百度百科的相关描述:
http://baike.baidu.com/view/32692.htm?fr=ala0_1_1
一开始,我在更新的时候,只调用了 entry.UpdateCredentials 这个方法,结果每次都拨的是同一个IP。我试了N种方法:取消当前的拨号尝试,断开当前的拨号试尝,甚至也想到删除这个连接,在重建,但都报错。后来才发现还有个 Update 方法。
 
 
2,异步拨号:
。。。
dialer.EntryName = VPNNAME;
//dialer.Timeout = 20000;
dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
dialer.StateChanged += new EventHandler<StateChangedEventArgs>(dialer_StateChanged);
dialer.DialCompleted += new EventHandler<DialCompletedEventArgs>(dialer_DialCompleted);
。。。
public static void DialAsync( string ip, string user, string pwd ) {
    CreateOrUpdateVPNEntry(ip, user, pwd);
    Disconnect();
    dialer.DialAsync();
}
 
public static void Disconnect() {
    dialer.DialAsyncCancel();
    foreach( RasConnection conn in dialer.GetActiveConnections() ) {
        if( conn.EntryName == VPNNAME ) {
            conn.HangUp();
            return;
        }
    }
}
 
这里有个 dailer.Timeout ,请不误解,这个 Timeout 不是尝试连接所使用的时间,而是如果连接成功了,会保持这个连接多长时间。
 
DotRas v1.1
 
我写的测试代码:
只是示例,没有进一步完善,基本上都上用异步方式处理的,代码有点乱,见笑。
 

Add comment


Security code
Refresh

Popular Contents

Recommend

Site Info

Members : 1
Content : 130
Web Links : 7
Content View Hits : 99641

Links