Jump to content
Simpel

Pull from NTP through proxy

Recommended Posts

Hi, 

I tried a function by @kor here: 

But it does not work through a proxy. So I tried a bit. With some forum help months ago I had a www-solution through a proxy for some other stuff. But trying it with ntp didn't work.

#include <WinHttp.au3>
Global Const $sProxy = "http://prx01.xxx.de:8080"
Global Const $sUserName = "UserName", $sPassword = "PassWord"
$vOpen = _WinHttpOpen(Default, $WINHTTP_ACCESS_TYPE_NAMED_PROXY, $sProxy)
$vConnect = _WinHttpConnect($vOpen, "pool.ntp.org", 123) ; Port 123
$vRequest = _WinHttpSimpleSendRequest_ProxyAuth($vConnect)
Global $sSource = _WinHttpSimpleReadData($vRequest)
ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $sSource = ' & $sSource & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
Exit

Func _WinHttpSimpleSendRequest_ProxyAuth($hConnect, $sType = Default, $sPath = Default, $sReferrer = Default, $sDta = Default, $sHeader = Default)
    Local $hRequest = _WinHttpSimpleSendRequest($hConnect, $sType, $sPath, $sReferrer, $sDta, $sHeader)
    If $hRequest Then
        Local $iStatusCode = _WinHttpQueryHeaders($hRequest, $WINHTTP_QUERY_STATUS_CODE)
        If $iStatusCode = $HTTP_STATUS_PROXY_AUTH_REQ Then
            Local $iSupportedSchemes, $iFirstScheme, $iAuthTarget ; Query Authorization scheme
            If _WinHttpQueryAuthSchemes($hRequest, $iSupportedSchemes, $iFirstScheme, $iAuthTarget) Then
                _WinHttpSetCredentials($hRequest, $iAuthTarget, $iFirstScheme, $sUserName, $sPassword) ; Set passed credentials
                _WinHttpSendRequest($hRequest)  ; Set passed credentials
                _WinHttpReceiveResponse($hRequest) ; And wait for the response again
            EndIf
        EndIf
    EndIf
    Return $hRequest
EndFunc

(This snippet only tries to get raw data.) 

$sSource is "". With no port (instead of 123) I only get the informations I see when I type url into a browser - so it's not the information I seek. (There is not time included in http source code.)

Some hints? Regards, Conrad


SciTE4AutoIt = 3.7.3.0   AutoIt = 3.3.14.2   AutoItX64 = 0   OS = Win7Pro SP1   OSArch = X64   Language = 0407/german
H:\...\AutoIt3\SciTE     H:\...\AutoIt3      H:\...\AutoIt3\Include     (H:\ = Network Drive)

   88x31.png  Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • By CYCho
      Based on codes in an old AutoIt Forum, I made the following code and it works perfectly. But I have couple of questions on how it works. I have to ask the original writer of this code(@Fzz), but he doesn't seem to be active now. Can someone please let me know the internal workings of this code? I'm especially curious about the meaning of packet sent to the NTP server.  I don't know what the 96-byte long hex string with a lot of 0's means. I don't know why the hex string is converted to a decimal character string instead of using the decimal characters to start with. I don't know the benefit of using Call() function over using funtion name followed by ().
      ;~ Many thanks to @TheXman for his kind guidance. ;~ https://www.autoitscript.com/forum/topic/200643-pulling-time-from-ntp-server/?do=findComment&comment=1439629 #Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_AU3Check_Parameters=-w 3 -w 4 -w 5 -w 6 -d #AutoIt3Wrapper_Outfile=NTP_Time_V4.exe #AutoIt3Wrapper_Res_Fileversion=4.0 #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** #RequireAdmin #include <Constants.au3> #include <Date.au3> Global $hTimeoutTimer = TimerInit() While 1 If Ping("www.google.com") > 0 Then ExitLoop If TimerDiff($hTimeoutTimer) > 120000 Then WriteLog(0, "System has no internet connection") Exit EndIf Sleep(50) WEnd Global $NTP_Server = 'time.google.com', $NTP_Time NTP_GetTime() System_SetTime() Func System_SetTime() ; 2019/10/28 23:09:52.522 ; 12345678901234567890123 Local $m = StringMid($NTP_Time, 6, 2) Local $d = StringMid($NTP_Time, 9, 2) Local $y = StringMid($NTP_Time, 1, 4) Local $h = StringMid($NTP_Time, 12, 2) Local $mi = StringMid($NTP_Time, 15, 2) Local $s = StringMid($NTP_Time, 18, 2) Local $ms = StringMid($NTP_Time, 21, 3) ;~ Sets the new current time to the computer Local $tCurr = _Date_Time_EncodeSystemTime($m, $d, $y, $h, $mi, $s, $ms) Local $tTime = _Date_Time_GetSystemTime() _Date_Time_SetSystemTime(DllStructGetPtr($tCurr)) Local $aTime = _Date_Time_SystemTimeToArray($tTime) WriteLog($aTime, "Update Time: " & $NTP_Time & " UTC") EndFunc ;==>System_SetTime Func NTP_GetTime() Local $tBuffer Local $aSocket Local $xRequest = Binary(""), $xResponse = Binary(""), $hTimeoutTimer, $hEchoTimer, $iDelay Local $iSeconds= 0, $iFractions = 0, $iMsecs = 0 ; Create the NTP request using a 48 byte buffer $tBuffer = DllStructCreate("byte[48]") DllStructSetData($tBuffer, 1, 0x23) ; 00 100 011 = LI(0) / VN(4-NTPv4) / Mode(3-Client) ; Copy the buffer to a variable for sending $xRequest = DllStructGetData($tBuffer, 1) ; Send NTP request UDPStartup() If @error Then WriteLog(0, "UDPStartup failed - @error = " & @error) Exit EndIf OnAutoItExitRegister("udp_shutdown") $aSocket = UDPOpen(TCPNameToIP($NTP_Server), 123) If @error Then WriteLog(0, "UDPOpen failed - @error = " & @error) Exit EndIf Sleep(50) $hTimeoutTimer = TimerInit() While 1 $hEchoTimer = TimerInit() UDPSend($aSocket, $xRequest) If @error Then WriteLog(0, "UDPSend failed - @error = " & @error) Exit EndIf Do $xResponse = UDPRecv($aSocket, DllStructGetSize($tBuffer), $UDP_DATA_BINARY) If @error Then WriteLog(0, "UDPRecv failed - @error = " & @error) Exit EndIf Until $xResponse <> Binary("") $iDelay = Round(TimerDiff($hEchoTimer)/2) If $iDelay < 100 Then ExitLoop EndIf If TimerDiff($hTimeoutTimer) > 120000 Then ; If no response within 2 seconds, then exit WriteLog(0, "UDPRecv timed out") Exit EndIf Sleep(100) WEnd ; Close the socket UDPCloseSocket($aSocket) ; Parse timestamp values ; - Current time is calculated from the xmit timestamp in NTP response header ; - Xmit timestamp seconds is a big-endian, uint32, at binary position 41 ; - Xmit timestamp fraction is a big-endian, uint32, at binary position 45 $iSeconds = Dec(Hex(BinaryMid($xResponse, 41, 4)), $NUMBER_64BIT) ; seconds since 1900-01-01 00:00:00 $iFractions = Dec(Hex(BinaryMid($xResponse, 45, 4)), $NUMBER_64BIT) ; the maximum value is 0xFFFFFFFF, which represents 1 second $iMsecs = Round($iFractions / 2^32 * 1000) + $iDelay ; It normally takes about 50 milsecs to get NTP time If $iMsecs >= 1000 Then $iSeconds += 1 $iMsecs -= 1000 EndIf ; Current NTP time $NTP_Time = _DateAdd("s", $iSeconds, "1900/01/01 00:00:00") & StringFormat(".%03i", $iMsecs) EndFunc ;==>NTP_GetTime Func udp_shutdown() UDPShutdown() EndFunc ;==>udp_shutdown Func WriteLog($pTime, $sMessage) Local $fn, $sTime If $pTime = 0 Then $fn = FileOpen(@ScriptDir & "\TimeSync Failed.log", 2) $sTime = _NowCalc() Else $fn = FileOpen(@ScriptDir & "\TimeSync.log", 2) FileDelete(@ScriptDir & "\TimeSync Failed.log") $sTime = StringFormat("System Time: %04d/%02d/%02d %02d:%02d:%02d.%03d UTC", $pTime[2], $pTime[0], $pTime[1], $pTime[3], $pTime[4], $pTime[5], $pTime[6]) EndIf FileWrite($fn, $sTime & @CRLF & $sMessage) FileClose($fn) EndFunc ;==>WriteLog  
      Edit: The above code is my latest version as of 2019/11/24, reflecting all the suggestions thankfully offered by @TheXman.
      Edit: The compiled version of this code(NTP_Time_V4.exe) was cleared by Microsoft Windows Defender from false detection as of Definition 1.305.2722.0. - 2019/11/24
       
       
      NTP_Time_V4.exe.zip
    • By ripdad
      This script is based on algorithm code from EnrMa.
      Updated: January 22, 2018
      Made improvements. Changes are in the script header.
      Known Issues: AutoIt x64 does not work properly with this script.
      Download: LocalProxyServer_v1.00.zip
       
    • By RyukShini
      #include "WinHttp.au3" #include <array.au3> #include <file.au3> #include <WinAPI.au3> #include <string.au3> #include <WindowsConstants.au3> #include <FileConstants.au3> #include <ListviewConstants.au3> #include <GUIConstantsEx.au3> #include <MsgBoxConstants.au3> ; Learning HTTP Requests with WinHTTP ; Global $idOP, $usr, $list, $idEXIT, $call HotKeySet("{ESC}", "Terminate") Local $hGUI = GUICreate("Learning", 750, 500, 223, 202, $WS_BORDER) Local $idEXIT = GUICtrlCreateButton("Exit", 660, 440, 75, Default) Local $idCon = GUICtrlCreateButton("Start", 10, 10, 725, Default) Local $siteLab = GUICtrlCreateLabel("Select Test", 20, 48 ,Default, 35) GUICtrlSetFont (-1,9, 800); bold Local $IG = GUICtrlCreateCheckbox("test", 75, 45) Local $realm = GUICtrlCreateCheckbox("test1", 75, 65) Local $site3 = GUICtrlCreateCheckbox("test2", 200, 45) Local $site4 = GUICtrlCreateCheckbox("test3", 200, 65) $list = GUICtrlCreateListView( " PROXY | NAME1 | NAME2 | STATUS ", 20, 100, 710, 300, $LVS_NOSORTHEADER+$LVS_SINGLESEL) GUISetState(@SW_SHOW, $hGUI) While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE, $idEXIT Exit Case $IG If _IsChecked($IG) Then $call = "test" EndIf Case $idCon Call($call) EndSwitch WEnd Func test() $url = "www.w3schools.com" $sPage = "/tags/demo_form.asp" Local $proxies Local $names _FileReadToArray("proxies.txt", $proxies) ; read the list of names to array _FileReadToArray("Okay.txt", $names) ; read the list of names to array For $i = 1 To UBound($proxies) - 1 $Read = $names[$i] $Datastring = ('') $newreadamount = _StringBetween($read,$Datastring, ':') $newreadamount[0] = StringReplace($newreadamount[0], ":", "") $name1 = $newreadamount[0] $Datastring2 = (':') $newreadamount2 = _StringBetween($read,$Datastring2, '') $newreadamount2[0] = StringReplace($newreadamount2[0], ":", "") $name2 = $newreadamount2[0] $sAdditionalData = "name1="&$name1&"&name2="&$name2 MsgBox(4096, "Test", $proxies[$i] & " - " & $name1&":"&$name2,1) ; Initialize and get session handle $hOpen = _WinHttpOpen("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0", $WINHTTP_ACCESS_TYPE_NAMED_PROXY, $proxies[$i]) _WinHttpSetTimeouts($hOpen, 15, 15, 15, 15) ; Get connection handle $hConnect = _WinHttpConnect($hOpen, $url) ; Make a request $hRequest = _WinHttpOpenRequest($hConnect, "POST", $sPage) ; Send it. Specify additional data to send too. This is required by the Google API: _WinHttpSendRequest($hRequest, "Content-Type: application/x-www-form-urlencoded", $sAdditionalData) ; Wait for the response _WinHttpReceiveResponse($hRequest) ; See what's returned Dim $sReturned If _WinHttpQueryDataAvailable($hRequest) Then ; if there is data Do $sReturned &= _WinHttpReadData($hRequest) Until @error EndIf ; Close handles _WinHttpCloseHandle($hRequest) _WinHttpCloseHandle($hConnect) _WinHttpCloseHandle($hOpen) ; See what's returned MsgBox(4096, "Returned", $sReturned, 1) If StringInStr($sReturned,'Input was received as:') Then GUICtrlCreateListViewItem($proxies[$i] & "|"&$name1&"|"&$name2&"|Success", $list) Sleep(500) ContinueLoop ElseIf $sReturned = "" Then FileWrite("nottested.txt",$name1&":"&$name2 & @CRLF) GUICtrlCreateListViewItem($proxies[$i] & "|"&$name1&"|"&$name2&"|Bad Proxy", $list) Sleep(500) ContinueLoop EndIf Next EndFunc Func Terminate() Exit 0 EndFunc Func _IsChecked($idControlID) Return BitAND(GUICtrlRead($idControlID), $GUI_CHECKED) = $GUI_CHECKED EndFunc ;==>_IsChecked This is my code and it runs just fine.
      My problem is that if I receive Bad Proxy I need it to test the request again with the same array input $name1 / $name2 until I receive
      'Input was received as:'
      So basically
       
      ElseIf $sReturned = "" Then FileWrite("nottested.txt",$name1&":"&$name2 & @CRLF) GUICtrlCreateListViewItem($proxies[$i] & "|"&$name1&"|"&$name2&"|Bad Proxy", $list) Sleep(500) TRY AGAIN WITH NEW PROXY AND SAME CREDENTIALS EndIf Is this possible and if so do you have either some example code and/or some helpfile I can read.

      Thanks in advance!
    • By RyukShini
      I am coding a country specific IP checker with a buddy, he made the website/api and I am coding a client to run through IPs.
      i split my IPs so it doesn't read the port instead of IP:PORT just IP, however after reading through every IP
      I need to add all ports back in their right place again so it becomes IP:PORT again, but this part made my head spin a bit.
      Any help is highly appreciated!
      Thanks in advance.
      #include <ColorConstants.au3> ; Including required files #include <GUIConstantsEx.au3> #include <file.au3> #include <Array.au3> #include <string.au3> #include <StringConstants.au3> Example() Func Example() While 1 Local $ip Local $ips = "18k.txt" ;sets file path Local $strFileContents = FileRead($ips) $Arrayips = StringRegExp($strFileContents,'((?:\d+)(?:\.\d+){3})',3) For $i = 1 To UBound($Arrayips) - 1 ; Creating the object $oHTTP = ObjCreate("winhttp.winhttprequest.5.1") $oHTTP.Open("GET", "http://mysite:8080/json/" & $Arrayips[$i], False) ; Post url ; Header data > $oHTTP.SetRequestHeader("Host", "mysite.xyz:8080") $oHTTP.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0") $oHTTP.SetRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8") $oHTTP.SetRequestHeader("Accept-Language", "en-US,en;q=0.5") $oHTTP.SetRequestHeader("DNT", "1") $oHTTP.SetRequestHeader("Connection", "keep-alive") $oHTTP.SetRequestHeader("Cache-Control", "max-age=0") ; Header data < ; Performing the Request $oHTTP.Send() $oReceived = $oHTTP.ResponseText $oStatusCode = $oHTTP.Status If $oStatusCode <> 200 then MsgBox(4096, "Response code", $oStatusCode) ExitLoop EndIf $file = FileOpen("Received.html", 2) ; The value of 2 overwrites the file if it already exists FileWrite($file, $oReceived) $read = FileRead("Received.html") ;read fil if StringInStr($read, '"US",') Then FileWrite("output.txt", $Arrayips[$i] & @CRLF) Else ContinueLoop EndIf ;Sends the post data with the given details Next WEnd EndFunc ;==>Example  
    • By Simpel
      Hi there.
      I'm testing this code:
      #include "WinHttp.au3" ; http://www.w3schools.com/php/demo_form_validation_escapechar.php $sUserName = "SomeUserName" $sEmail = "some.email@something.com" $sDomain = "www.w3schools.com" $sPage = "/php/demo_form_validation_escapechar.php" ; Data to send $sAdditionalData = "name=" & $sUserName & "&email=" & $sEmail ; Initialize and get session handle $hOpen = _WinHttpOpen("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0") ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $hOpen = ' & $hOpen & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console ; Get connection handle $hConnect = _WinHttpConnect($hOpen, $sDomain) ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $hConnect = ' & $hConnect & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console ; Make a request $hRequest = _WinHttpOpenRequest($hConnect, "POST", $sPage) ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $hRequest = ' & $hRequest & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console ; Send it. Specify additional data to send too. This is required by the Google API: $hSendRequest = _WinHttpSendRequest($hRequest, "Content-Type: application/x-www-form-urlencoded", $sAdditionalData) ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $hSendRequest = ' & $hSendRequest & @CRLF & '>Error code: ' & @error & @TAB & "@extended: " & @extended & @CRLF) ;### Debug Console ; Wait for the response $hReceiveResponse = _WinHttpReceiveResponse($hRequest) ; See what's returned Dim $sReturned If _WinHttpQueryDataAvailable($hRequest) Then ; if there is data Do $sReturned &= _WinHttpReadData($hRequest) Until @error EndIf ; Close handles _WinHttpCloseHandle($hRequest) _WinHttpCloseHandle($hConnect) _WinHttpCloseHandle($hOpen) ; See what's returned ConsoleWrite("Returned: " & $sReturned & @CRLF) But sending a request fails.
      Console outputs this:
      >Running:(3.3.12.0) ... --> Press Ctrl+Alt+F5 to Restart or Ctrl+Break to Stop @@ Debug(14) : $hOpen = 0x00000000007DF540 >Error code: 0 @@ Debug(18) : $hConnect = 0x00000000008271C0 >Error code: 0 @@ Debug(22) : $hRequest = 0x00000000008B88E0 >Error code: 0 @@ Debug(26) : $hSendRequest = 0 >Error code: 1 @extended: 0 Returned: +>17:00:18 AutoIt3.exe ended.rc:0 +>17:00:18 AutoIt3Wrapper Finished. >Exit code: 0    Time: 0.6003 I'm testing it at work. There, we always have to identify at a proxy to be allowed to go to internet. But requests via inet.au3 will work. Maybe our firewall will block the request?
      Any ideas? I don't have any possibilities to test at home, because of OSX.
       
      Regards, Conrad
×
×
  • Create New...