How to automatically run ADSL dial when starting the machine (1)

zhaozj2021-02-17  54

We usually hope that there is a machine to hang online, and now there is ADSL monthly service, this is not a problem. But recently ADSL will always disconnect, when I want to copy some files from the company's machine, I sometimes find it can't be connected. So I have the functions you want to achieve, one is to implement ADSL dialing, and the other is to detect the network status timing, the third is to run when starting the machine (not only register as a service) Let's take a look. Do a dial-up program first build a RAS dialing unit file (this is the online collected) Unit Ras;

Interface

Uses Windows, Sysutils;

{$ Define Winver400} const rasunitversion = 110; Copyright: String = 'rasunit (c) 97-98 F. Piette v1.10'; rasapi32 = 'rasapi32.dll';

Unlen = 256; // maximum user name length pwlen = 256; // maximum password length cnlen = 15; // computer name length length DNLEN = CNLEN; // Maximum Domain Name Length

RAS_MAXDEVICETYPE = 16; ras_maxphonenumber = 128; ras_maxipaddress = 15; ras_maxipxaddress = 21;

{$ IFDEF WINVER400} RAS_MaxEntryName = 256; RAS_MaxDeviceName = 128; RAS_MaxCallbackNumber = RAS_MaxPhoneNumber; {$ ELSE} RAS_MaxEntryName = 20; RAS_MaxDeviceName = 32; RAS_MaxCallbackNumber = 48; {$ ENDIF}

RAS_MAXAREACODE = 10; ras_maxpadType = 32; ras_maxx25address = 200; ras_maxfacilities = 200; ras_maxuserdata = 200;

RASCS_OpenPort = 0; RASCS_PortOpened = 1; RASCS_ConnectDevice = 2; RASCS_DeviceConnected = 3; RASCS_AllDevicesConnected = 4; RASCS_Authenticate = 5; RASCS_AuthNotify = 6; RASCS_AuthRetry = 7; RASCS_AuthCallback = 8; RASCS_AuthChangePassword = 9; RASCS_AuthProject = 10; RASCS_AuthLinkSpeed ​​= 11; RASCS_AuthAck = 12; RASCS_ReAuthenticate = 13; RASCS_Authenticated = 14; RASCS_PrepareForCallback = 15; RASCS_WaitForModemReset = 16; RASCS_WaitForCallback = 17; RASCS_Projected = 18; {$ IFDEF WINVER400} RASCS_StartAuthentication = 19; RASCS_CallbackComplete = 20; RASCS_LogonNetwork = 21; {$ ENDIF} RASCS_SubEntryConnected = 22 Rascs_suBENTRYDISCONNECTED = 23;

RASCS_PAUSED = $ 1000; RASCS_Interactive = RASCS_PAUSED; RASCS_RetryAuthentication = (RASCS_PAUSED 1); RASCS_CallbackSetByCaller = (RASCS_PAUSED 2); RASCS_PasswordExpired = (RASCS_PAUSED 3);

Rascs_done = $ 2000; rascs_connected = rascs_done; rascs_disconnected = (rascs_done 1);

.. // If using RasDial message notifications, get the notification message code // by passing this string to the RegisterWindowMessageA () API // WM_RASDIALEVENT is used only if a unique message can not be registered RASDIALEVENT = 'RasDialEvent'; WM_RASDIALEVENT = $ CCCD ;

// TRASPROJECTION RASP_Amb = $ 10000; RASP_PppNbf = $ 0803F; RASP_PppIpx = $ 0802B; RASP_PppIp = $ 08021; RASP_Slip = $ 20000; type THRASCONN = THandle; PHRASCONN = ^ THRASCONN; TRASCONNSTATE = DWORD; PDWORD = ^ DWORD; PBOOL = ^ BOOL;

TRASDIALPARAMS = packed record dwSize: DWORD; szEntryName: array [0..RAS_MaxEntryName] of Char; szPhoneNumber: array [0..RAS_MaxPhoneNumber] of Char; szCallbackNumber: array [0..RAS_MaxCallbackNumber] of Char; szUserName: array [0. Ion [0..pwlen] of char; szdomain: array [0..dnlen] of char; {$ ifdef Winver401} dwsubentry: dword; dwsubentry: dword; {$ e}} szpadding: array [0..2] of char; end; PrasdialParams = ^ TraseDialParams;

TRASDIALEXTENSIS = PACKED Record Dwsize: DWORD; DWFOPTIONS: DWORD; HWNDPARENT: HWND; Reserved: DWORD; END; PRASDIALEXTENSIONS =

TRASCONNSTATUS = packed record dwSize: DWORD; RasConnState: TRASCONNSTATE; dwError: DWORD; szDeviceType: array [0..RAS_MaxDeviceType] of char; szDeviceName: array [0..RAS_MaxDeviceName] of char; szPadding: array [0..1] of Char; end; prasconnstatus = ^ trasconnstatus;

TRASCONN = packed record dwSize: DWORD; hRasConn: THRASCONN; szEntryName: array [0..RAS_MaxEntryName] of char; {$ IFDEF WINVER400} szDeviceType: array [0..RAS_MaxDeviceType] of char; szDeviceName: array [0..RAS_MaxDeviceName] of char; {$ ENDIF} szPadding: array [0..0] of char; end; PRASCONN = ^ TRASCONN; TRASENTRYNAME = packed record dwSize: DWORD; szEntryName: array [0..RAS_MaxEntryName] of char; szPadding: array [ 0..2] of char; end; PRASENTRYNAME = ^ TRASENTRYNAME

TRASENTRYDLG = packed record dwSize: DWORD; hWndOwner: HWND; dwFlags: DWORD; xDlg: LongInt; yDlg: LongInt; szEntry: array [0..RAS_MaxEntryName] of char; dwError: DWORD; Reserved: DWORD; Reserved2: DWORD; szPadding: Array [0..2] of char; end; PRASENTRYDLG = ^ TRASENTRYDLG;

Trasprojection = Integer; traspppip = record dwsize: dword; dwerror: dword; szipaddress: array [0..ras_maxipaddress] of char; end;

function RasDialA (RasDialExtensions: PRASDIALEXTENSIONS; PhoneBook: PChar; RasDialParams: PRASDIALPARAMS; NotifierType: DWORD; Notifier: Pointer; RasConn: PHRASCONN): DWORD; stdcall; function RasGetErrorStringA (uErrorValue: DWORD; // error to get string for szErrorString: PChar; // buffer to hold error string cBufSize: DWORD // size, in characters, of buffer): DWORD; stdcall; function RasHangupA (RasConn: THRASCONN): DWORD; stdcall; function RasConnectionStateToString (nState: Integer): String; function RasGetConnectStatusA ( Hrasconn: thrasconn; // handle to ras connection of interest lprasconnstatus: PrasconnStatus // Buffer to receive; stdcall; function rasenumconnectionsa (Prasconn: Prasconnections) uffer to receive connections data pCB: PDWORD; // size in bytes of buffer pcConnections: PDWORD // number of connections written to buffer): DWORD; stdcallfunction RasEnumEntriesA (Reserved: Pointer; // reserved, must be NIL szPhonebook: PChar; / / full path and filename of phonebook file lpRasEntryName: PRASENTRYNAME; // buffer to receive entries lpcb: PDWORD; // size in bytes of buffer lpcEntries: PDWORD // number of entries written to buffer): DWORD; stdcall; function RasGetEntryDialParamsA (lpszPhonebook : Pchar;

// pointer to the full path and filename of the phonebook file lprasdialparams: PRASDIALPARAMS; // pointer to a structure that receives the connection parameters lpfPassword: PBOOL // indicates whether the user's password was retrieved): DWORD; stdcall; function RasEditPhonebookEntryA (hWndParent : HWND; // handle to the parent window of the dialog box lpszPhonebook: PChar; // pointer to the full path and filename of the phonebook file lpszEntryName: PChar // pointer to the phonebook entry name): DWORD; stdcall; // function RasEntryDlgA (// lpszPhonebook: PChar; // pointer to the full path and filename of the phone-book file // lpszEntry: PChar; // pointer to the name of the phone-book entry to edit, copy, or create / / Lpinfo: PRASENTRYDLG / / POINTER TO A Structure That Contains Additional Paramet ers //): DWORD; stdcall; function RasCreatePhonebookEntryA (hWndParent: HWND; // handle to the parent window of the dialog box lpszPhonebook: PChar // pointer to the full path and filename of the phonebook file): DWORD; stdcall;

function RasGetProjectionInfoA (hRasConn: THRASCONN; // handle that specifies remote access connection of interest RasProjection: TRASPROJECTION; // specifies type of projection information to obtain lpProjection: Pointer; // points to buffer that receives projection information lpcb: PDWORD // points to Variable what specifies buffer size: dword; stdcall; function rasgetipaddress: string; import;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} Function rasconnectionStateTstring (NState: integer): String ; begin case nState of RASCS_OpenPort: Result: = 'Opening Port'; RASCS_PortOpened: Result: = 'Port Opened'; RASCS_ConnectDevice: Result: = 'Connecting Device'; RASCS_DeviceConnected: Result: = 'Device Connected'; RASCS_AllDevicesConnected: Result: = 'All Devices Connected'; RASCS_Authenticate: Result: = 'Starting Authentication'; RASCS_AuthNotify: Result: = 'Authentication Notify'; RASCS_AuthRetry: Result: = 'Authentication Retry'; RASCS_AuthCallback: Result: = 'Callback Requested'; RASCS_AuthChangePassword: Result: = 'Change Password Requested'; RASCS_AuthProject: Result: = 'Projection Phase Started'; RASCS_AuthLinkSpeed: Result: = 'Link Speed ​​Calculation'; RASCS_AuthAck: Result: = 'Authentication Acknowl edged '; RASCS_ReAuthenticate: Result: =' Reauthentication Started '; RASCS_Authenticated: Result: =' Authenticated '; RASCS_PrepareForCallback: Result: =' Preparation For Callback '; RASCS_WaitForModemReset: Result: =' Waiting For Modem Reset '; RASCS_WaitForCallback: Result: = 'Waiting for Callback'; rascs_projected: Result: = 'Projected'; {$ IFDEF WINVER400} Rascs_StartAuthentication: Result: = 'Start Authentication';

RASCS_CallbackComplete: Result: = 'Callback Complete'; RASCS_LogonNetwork: Result: = 'Logon Network'; {$ ENDIF} RASCS_SubEntryConnected: Result: = ''; RASCS_SubEntryDisconnected: Result: = ''; RASCS_Interactive: Result: = 'Interactive'; RASCS_RetryAuthentication : Result: = 'Retry Authentication'; RASCS_CallbackSetByCaller: Result: = 'Callback Set By Caller'; RASCS_PasswordExpired: Result: = 'Password Expired'; RASCS_Connected: Result: = 'Connected'; RASCS_Disconnected: Result: = 'Disconnected'; else Result: = 'Connection State #' INTOSTR (NSTATE); End; End; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function RasGetIPAddress: string; var RASConns: TRasConn; dwSize: DWORD; dwCount: DWORD; RASpppIP: TRASPPPIP; begin Result: = ''; RASConns.dwSize: = SizeOf (TRASConn); RASpppIP. DWSIZE: = SizeOf (Rasppip); dwsize: = SizeOf (RASConns); if RASEnumConnectionsA (@RASConns, @dwSize, @dwCount) = 0 then begin if dwCount> 0 then begin dwSize: = SizeOf (RASpppIP); RASpppIP.dwSize: = SizeOf (RASpppIP); if RASGetProjectionInfoA (RASConns. Hrasconn, rasp_pppip, @raspppip, @dwsize) = 0 THEN Result: = strPas (raspppip.szipaddress); end; end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} Function rasdia; external rasapi32 name 'rasdiala' ; function RasGetErrorStringA; external rasapi32 name 'RasGetErrorStringA'; function RasHangUpA; external rasapi32 name 'RasHangUpA'; function RasGetConnectStatusA; external rasapi32 name 'RasGetConnectStatusA'; function RasEnumConnectionsA; external rasapi32 name 'RasEnumConnectionsA'; function RasEnumEntriesA; external rasapi32 name 'RasEnumEntriesA' ; function RasGetEntryDialParamsA; external rasapi32 name 'RasGetEntryDialParamsA'; function RasEditPhonebookEntryA; external rasapi32 name 'RasEditPhonebookEntryA'; // function RasEntryDlgA; external rasapi32 name 'RasEntryDlgA'; function RasCreatePhonebookEntryA; external rasapi32 name 'RasCreatePhonebookEntryA'; function RasGetProjectionInfoA; external rasapi32 name ' RasgetProjectionInfoa '; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}

End.

With these functions, you can then do your own dialing programs.

PROGRAM Autodial;

{$ Apptype console}

Uses sysutils, infiles, windows, winsock, ras in 'ras.pas';

var DirPath, EntryName, UserName, PassWord, VisitHost, VisitUrl, VisitParam: string; CheckVisit: Boolean; nRasConnCount: DWORD; aRasConn: array [0..10] of TRASCONN; hRasConn: THRASCONN; f: TIniFile; IsConnected: boolean; procedure LogMessage (Msg: string); var LogFile: TextFile; begin try AssignFile (LogFile, DirPath 'Log.txt'); Append (LogFile); WriteLn (LogFile, DateTimeToStr (Now) ',' Msg); CloseFile (LogFile Writeln (DateTimetostr (NOW) ',' MSG); Except end;

END;

function GetIP: string; var IPAddr: String; begin IPAddr: = RasGetIPAddress; if IPAddr> '' then result: = IPAddr else result: = 'Unknown'; end; function InitSocket (var ASocket: TSocket; AAddr: string; APort: INTEGER; atimeout: integer: Integer; var mywsa: wsadata; sin: tsockaddr; begin result: = 0; if Wsastartup (MakeWord (2, 2), mywsa) <> 0 THEN // Initialization Begin WSacleanup; Result: = 1 ; Exit; end; ASocket: = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); // create socket If ASocket = INVALID_SOCKET Then Begin WSACleanup; Result: = 2; Exit; End; SIN.sin_family: = AF_INET; SIN.sin_port: = Htons (Aport); sin.sin_addr.s_addr: = inet_addr (Pchar (AADDR)); if Connect (Asocket, SIN, SIZEOF (SIN) = SOCKET_ERROR THEN BEGIN ClossoSocket; WSACLANUP; Result: = 9; End; if setsockopt (Asocket, SOL_Socket, SO_RCVTIMEO, PCHAR (@Atimeout) = SOCKET_ERROR THEN / / Settings The timeout is 3 seconds Begin CloseSocket (Asocket); wsacleanup; Result: = 6; EXIT; END; IF S Etsockopt (Asocket, SOL_Socket, So_Sndtimeo, Pchar (@ATIMEOUT), SIZEOF (Atimeout) = Socket_ERROR THEN / / Settings Send Time for 3 seconds Begin CloseSocket (Asocket); wsacleanup; Result: = 7; End; end;

Procedure Uninitsocket; Begin Try CloseSocket (ASOCKET); // Close Socket Wsacleanup; Except End;

After the dial completion of Procedure AfterConnect; //, access the specified page, let's record the IP address so that we can know the new IP address after the dialing of the dial, VAR HSocket: Tsocket; Saddr, SendText: String; SendBuf: Array [0..1024] of char; hostent: phostent;

Begin Try if NOT Checkvisit Then Begin LogMessage ('--------' getip "-------- '); isconnected: = true; exit; end; hostent: = gethostbyname (Pchar (Visithost)); if hostent <> nil the beginning = format ('% d.% d.% d.% d', [byte (h_addr ^ [0]), Byte (h_addr ^ [1]), Byte (h_addr ^ [2]), byte (h_addr ^ [3])]);

INITSOCKET (HSocket, Saddr, 80, 10000); Sendtext: = 'POST' VISITURL 'HTTP / 1.1' # 13 # 10 'Accept: Image / GIF, Image / X-Xbitmap, Image / JPEG, Image / PJPEG , Application / VND.ms-Excel, Application / VND.ms-PowerPoint, Application / MSWORD, * / * ' # 13 # 10 ' Referr: ' # 13 # 10 ACCEPT-LANGUAGE: EN-CH-CN' # 13 # 10 'Content-Type: Application / X-WWW-FORM-URLENCODED' # 13 # 10 'Accept-Encoding: Gzip, Deflate' # 13 # 10 'User-Agent: Mozilla / 4.0 (Compatible; Msie 6.0; Windows NT 5.1; .NET CLR 1.0.3705) ' # 13 # 10 ' Host: ' Visithost # 13 # 10 ' Content-Length: ' INTOSTOSTR (Length (Visitparam)) # 13 # 10 'Connection: Keep-Alive' # 13 # 10 'Cache-Control: No-cache' # 13 # 10 'cookie:' # 13 # 10 # 13 # 10 VisitParam # 13 # 10; Fillchar (Sendbuf, Sizeof (Sendbuf), 0); Strlcopy (Sendbuf, Pchar (SendText), Length (SendText); Send (HSocket, Sendbuf, Length (SendText), 0);

Uninitsocket (HSocket);

LogMessage ('----------------------'); isconnected: = true; except end; end; procedure disconnected; begin try if harasconn <> 0 THEN BEGIN RASHANGUPA (HRASCONN); HRASCONN: = 0; End; Except end;

Procedure getActiveConn; VAR DWRET: DWORD; NCB: DWORD; BUF: Array [0..255] of char; begin try arasconn [0] .dwsize: = sizeof (Arasconn [0]); NCB: = SizeOf (Arasconn); DWRET: = RaseNumConnectionsa (@Arasconn, @ncb, @nrasconncount); if dwret <> 0 THEN BEGIN RASGETERRORSTRINGA (DWRET, @BUF [0], SIZEOF (BUF)); LogMessage (BUF); End; Except end;

function GetActiveConnHandle (szName: String): THRASCONN; var I: Integer; begin GetActiveConn; if nRasConnCount> 0 then begin for I: = 0 to nRasConnCount - 1 do begin if StrIComp (PChar (szName), aRasConn [I] .szEntryName) = 0 THEN Begin Result: = Arasconn [i] .hrasconn; EXIT; End; end; end; result: = 0;

Function checkconn: boolean; begin hrasconn: = getactiveconnhandle (fentryName); if hrasconn <> 0 Then Result: = true else result: = false;

procedure RasDialFunc (unMsg: DWORD; FRasConnState: TRASCONNSTATE; FdwError: DWORD); stdcall; var Buf: array [0..255] of Char; begin try LogMessage (RasConnectionStateToString (FRasConnState)); if FRasConnState = RASCS_Connected then begin AfterConnect; end Else if FrasconnState = rascs_disconnected the beginninga (fdwerror, @buf [0], sizeof (buf)); logMessage (buf); disconnected; end; end;

procedure Dial (FEntryName, FUserName, FPassword: String); var rdParams: TRASDIALPARAMS; dwRet: DWORD; Buf: array [0..255] of Char; begin try hRasConn: = GetActiveConnHandle (FEntryName); if hRasConn <> 0 then begin LogMessage ('Connection Already Active'; "EXIT; END;

// setup RAS Dial Parameters FillChar (rdParams, SizeOf (rdParams), 0); rdParams.dwSize: = SizeOf (TRASDIALPARAMS); strCopy (rdParams.szUserName, PChar (FUserName)); strCopy (rdParams.szPassword, PChar (FPassword) ); Strcopy (rdparams.szentryname, pchar (fentryname)); rdparams.szphonenumber [0]: = # 0; rdparams.szcallbacknumber [0]: = '*'; rdparams.szdomain: = '*';

Hrasconn: = 0; DWRET: = Rasdiaala (nil, nil, @rdparams, 0, @rasdialfunc, @hrasconn); if dwret <> 0 Then Begin RasgeTerrorStringA (dwret, @BUF [0], SIZEOF (BUF)); LogMessage (INTTOSTR (DWRET) '' BUF); DISCONNECTED; END ELSE BEGIN logMessage ('DIALING' ''); END; End End;

Begin Try DirPath: = ExtractFilePath (paramstr (0)); f: = tinifile.create (DirPath 'conf.ini'); entryName: = f.readstring ('rasdial', 'entryname "; username: = F.ReadString ('rasdial', 'username', '); password: = f.readstring (' rasdial ',' password ','); checkvisit: = f.readbool ('rasdial', 'visit', False); Visithost: = f.readstring ('rasdial', 'host', '); visiturl: = f.readstring (' rasdial ',' url ',' '); Visitparam: = F.Readstring (' Rasdial ',' Param ',' '); f.free; if not checkconn (entryName) THEN Begin

Dial (EntryName, Username, Password);

END ELSE BEGIN logMessage ('--------' getip "---------- '); isconnected: = true; end; while not isconnected do sleep (1000); Except End;

After compiling, generate a console application, write your own conf.ini, fill in your own connection name, user name, password, etc., you can automatically dial it.

Source code download

http://ono.3322.org

转载请注明原文地址:https://www.9cbs.com/read-30259.html

New Post(0)