协议模拟编程之ADSL模式下IP自动换

来源:互联网 发布:新浪网络传真 编辑:程序博客网 时间:2024/04/29 20:20

在编写一些自动发贴机之类的小软件时,经常会用到自动更换IP的地方,手动切换的话太麻烦了,因此我们总会相当用脚本或自动化程序来代替手工切换ip的活。如果家里连的是“宽带连接”,几句命令就可以自动切换了。

set WShell=createobject("WScript.Shell")

WShell.run "RasDial 宽带连接 /Disconnect",vbhide,true

WShell.run "RasDial 宽带连接 用户名 密码",vbhide,true


注意保存为Vbs脚本,如上图。这是很简单的脚本完成的功能,它可以隐藏运行。

下面我们还是说说用C#的代码完成IP自动切换,毕竟很多程序如果手动去切换IP会很不协调,程序会运行出错。

要将已经存在的ADSL宽带连接从连接状态断开,然后再连接,从而强制重新自动分配IP,从而改变IP,完成一系列这样的功能,除了显式调用上述代码中的“RasDial.exe”之外,在网上还可以引用System32目录下的“rasapi32.dll”,以及"Wininet.dll ”一种方法。

下面是具体步骤:

1.引用命名空间:

using System.Runtime.InteropServices;

接下来就是调用Wininet.dll的API函数,用于宽带网络拨号

[System.Runtime.InteropServices.DllImport("Wininet.dll")]

      public static extern Int32 InternetDial(IntPtr hwndParent,string lpszConnectoid,

Int32 dwFlags, ref Int32 lpdwConnection, Int32 dwReserved);     

顺带申明一下这个函数所引用的类型,这些类型都是直接从Pinvoke.net查找并复制过来的,用于填补InternetDial的参数dwFlags,INTERNET_DIAL_SHOW_OFFLINE是手动拨号(将“取消”按钮替换为“脱机工作”按钮),INTERNET_DIAL_FORCE_PROMPT是系统提示下的手动拨号, INTERNET_DIAL_UNATTENDED是自动拨号。

[Flags]
     public enum InternetDialFlags
      {
          INTERNET_DIAL_FORCE_PROMPT = 0x2000,
          INTERNET_DIAL_SHOW_OFFLINE = 0x4000,
          INTERNET_DIAL_UNATTENDED = 0x8000
      }

这样一来,我们就可以直接调用这样一句函数用于连接网络了。

 int temp =0;

         Adsl.InternetDial(IntPtr.Zero,"", (int)Adsl.InternetDialFlags.INTERNET_DIAL_UNATTENDED,ref temp, 0);

接下来断开网络就稍微"复杂"一点了,先让我们引用RasHangUp这样一个API32函数。这里顺便将RasHangUp需要用的参数类型和结构都直接申明在里面了。

public const int RAS_MaxDeviceType = 16;
      public const int RAS_MaxDeviceName = 128;
      public const int MAX_PATH = 260;
      public const int ERROR_BUFFER_TOO_SMALL = 603;
      public const int ERROR_SUCCESS = 0;

        [StructLayout(LayoutKind.Sequential, Pack = 4, CharSet = CharSet.Auto)]
         public struct RASCONN
{
    public int dwSize;
    public IntPtr hrasconn;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = RAS_MaxEntryName)]
    public string szEntryName;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = RAS_MaxDeviceType)]
    public string szDeviceType;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = RAS_MaxDeviceName)]
    public string szDeviceName;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
    public string szPhonebook;
    public int dwSubEntry;
    public Guid guidEntry;
    public int dwFlags;
    public Guid luid;                                                   
}
        [DllImport("rasapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern int RasEnumConnections(
            [In, Out] RASCONN[] rasconn,
            [In, Out] ref int cb,
            [Out] out int connections);
      public const int RAS_MaxEntryName = 256;
       //挂断拨号,断开网络链接
      [DllImport("rasapi32.dll", SetLastError = true)]
     public static extern uint RasHangUp(IntPtr hRasConn);


函数部分就完成了,接下来我们可以这样写:

public void DisConnect()
      {
           System.Adsl.RASCONN[] connections = new System.Adsl.RASCONN[1];//创建新连接
          connections[0].dwSize = Marshal.SizeOf(typeof(System.Adsl.RASCONN)); //未连接申请内存空间
          int connectionCount = 0;//设置连接数
          int cb = Marshal.SizeOf(typeof(System.Adsl.RASCONN));//
          int ret = Adsl.RasEnumConnections(connections, ref cb, out connectionCount);
           Adsl.RasHangUp(connections[0].hrasconn);
            
      }


代码实在是很简单,一看就明白,因此没必要多啰嗦了,相信各位比我还在行。这个也就是很久以前就流行于网络的方法了。但是这样一个方法其实并不是总能兼容地跑在我们各种各样的机器上,很多电脑和网络环境其实都无法真正实现。

在这里干脆给大家添上上述功能实现的完整代码吧,以免被我说得思路更加不清晰了。^.^

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace System
{
    /// <summary>
    /// http://www.cnblogs.com/uu102
    /// 凌晨的搜索者
    /// </summary>
   public class Adsl
    {
      public const int RAS_MaxDeviceType = 16;
      public const int RAS_MaxDeviceName = 128;
      public const int MAX_PATH = 260;
      public const int ERROR_BUFFER_TOO_SMALL = 603;
      public const int ERROR_SUCCESS = 0;

        [StructLayout(LayoutKind.Sequential, Pack = 4, CharSet = CharSet.Auto)]
         public struct RASCONN
{
    public int dwSize;
    public IntPtr hrasconn;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = RAS_MaxEntryName)]
    public string szEntryName;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = RAS_MaxDeviceType)]
    public string szDeviceType;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = RAS_MaxDeviceName)]
    public string szDeviceName;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
    public string szPhonebook;
    public int dwSubEntry;
    public Guid guidEntry;
    public int dwFlags;
    public Guid luid;                                                   
}
        [DllImport("rasapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern int RasEnumConnections(
            [In, Out] RASCONN[] rasconn,
            [In, Out] ref int cb,
            [Out] out int connections);
      public const int RAS_MaxEntryName = 256;
       //挂断拨号,断开网络链接
      [DllImport("rasapi32.dll", SetLastError = true)]
     public static extern uint RasHangUp(IntPtr hRasConn);
    
      [Flags]
     public enum InternetDialFlags
      {
          INTERNET_DIAL_FORCE_PROMPT = 0x2000,
          INTERNET_DIAL_SHOW_OFFLINE = 0x4000,
          INTERNET_DIAL_UNATTENDED = 0x8000
      }
      [System.Runtime.InteropServices.DllImport("Wininet.dll")]
      public  static extern Int32 InternetDial(IntPtr hwndParent, string lpszConnectoid, Int32 dwFlags, ref Int32 lpdwConnection, Int32 dwReserved);
      public void DisConnect()
      {
           System.Adsl.RASCONN[] connections = new System.Adsl.RASCONN[1];//创建新连接
          connections[0].dwSize = Marshal.SizeOf(typeof(System.Adsl.RASCONN)); //未连接申请内存空间
          int connectionCount = 0;//设置连接数
          int cb = Marshal.SizeOf(typeof(System.Adsl.RASCONN));//
          int ret = Adsl.RasEnumConnections(connections, ref cb, out connectionCount);
           Adsl.RasHangUp(connections[0].hrasconn);
            
      }
      public string AdslName { get; set; }
      public string Uid { get; set; }
      public string Pwd { get; set; }
      public Adsl(string adslName, string uid, string pwd)
      {
          this.AdslName = adslName;
          this.Uid = uid;
          this.Pwd = pwd;

      }
      public System.Diagnostics.Process Connect()
      {
          /* int temp = 0;
         Adsl.InternetDial(IntPtr.Zero, "", (int)Adsl.InternetDialFlags.INTERNET_DIAL_UNATTENDED, ref temp, 0);*/
          System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
          startInfo.FileName = "RasDial";
          if (string.IsNullOrEmpty(this.AdslName)) this.AdslName= "宽带连接";
          startInfo.Arguments = string.Format("{0} {1} {2}",this.AdslName,this.Uid,this.Pwd);
          startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
          System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo);
          return process;
      }
      public System.Diagnostics.Process ReDial()
      {
          DisConnect();
         return  Connect();
      }
     public static System.Diagnostics.Process ClearCookies(string cmd)
      {
          System.Diagnostics.Process p = new System.Diagnostics.Process();
          p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
          p.StartInfo.FileName = "RunDll32.exe";
          // 关闭Shell的使用
          p.StartInfo.UseShellExecute = false;
          // 重定向标准输入
          p.StartInfo.RedirectStandardInput = true;
          // 重定向标准输出
          p.StartInfo.RedirectStandardOutput = true;
          //重定向错误输出
          p.StartInfo.RedirectStandardError = true;
          p.StartInfo.CreateNoWindow = true;

          p.Start();
          p.StandardInput.WriteLine(cmd);
          p.StandardInput.WriteLine("exit");
          return p;
      }



    }
 
}

以上所述是PPPOE下连接方法,如果是路由器下的连接,则有很大不同,由于时间关系,下次再补充说说 路由器下自动更换IP的实现吧!



0 0
原创粉丝点击