Snippets ( Internet ): Difference between revisions

From AutoIt Wiki
Jump to navigation Jump to search
No edit summary
(Undo revision 13655 by Spudw2k (talk))
 
(2 intermediate revisions by the same user not shown)
Line 275: Line 275:
<syntaxhighlight lang="autoit">
<syntaxhighlight lang="autoit">
Local $aSubnetMaskIP1[] = [255,255,255,0]
Local $aSubnetMaskIP1[] = [255,255,255,0]
ConsoleWrite("Is SubnetMask Valid: " & _IsSubnetMaskValid($aSubnetMaskIP1) & @CRLF)
ConsoleWrite("Is SubnetMask Valid: " & _IsValidSubnetMask($aSubnetMaskIP1) & @CRLF)


Local $aSubnetMaskIP2[] = [255,248,0,0]
Local $aSubnetMaskIP2[] = [255,248,0,0]
ConsoleWrite("Is SubnetMask Valid: " & _IsSubnetMaskValid($aSubnetMaskIP2) & @CRLF)
ConsoleWrite("Is SubnetMask Valid: " & _IsValidSubnetMask($aSubnetMaskIP2) & @CRLF)


Local $aSubnetMaskIP3[] = [255,255,255,1]
Local $aSubnetMaskIP3[] = [255,255,255,1]
ConsoleWrite("Is SubnetMask Valid: " & _IsSubnetMaskValid($aSubnetMaskIP3) & @CRLF)
ConsoleWrite("Is SubnetMask Valid: " & _IsValidSubnetMask($aSubnetMaskIP3) & @CRLF)


Func _IsSubnetMaskValid($aIP)
Func _IsValidSubnetMask($aIP)
If Not UBound($aIP)=4 Then Return SetError(1,0,False) ;Validate Input (4 element array)
If Not UBound($aIP)=4 Then Return SetError(1,0,False) ;Validate Input (4 element array)


Line 301: Line 301:


     Return $bIsValid
     Return $bIsValid
EndFunc  ;==>_IPSubnetMaskIsValid
EndFunc  ;==>_IsValidSubnetMask
</syntaxhighlight>
</syntaxhighlight>



Latest revision as of 05:16, 30 June 2017


Please always credit an author in your script if you use their code. It is only polite.


Auto-Check For User To Update

Author: Valuater








; Auto-Check For User To Update

Global $Udif, $QT_web = "www.XPCleanMenu.HostRocket.com"
Call("Set_Updater")

;test
$Uask = MsgBox(68, "Update Notification", " Your last update was more than " & $Udif & " days ago." & @CRLF & @CRLF & "Would you like to check for new updates now?")

If $Uask = 6 Then MsgBox(0, "", "Success.  The update was ran.")

Func Set_Updater()
	If Not FileExists(@SystemDir & "\UpDate.dat") Then
		FileWrite(@SystemDir & "\UpDate.dat", @YDAY)
	Else
		$Uold = FileReadLine(@SystemDir & "\UpDate.dat", 1)

		If $Uold >=320 Then
			FileDelete(@SystemDir & "\UpDate.dat")
			Return
		EndIf

		$Udif = @YDAY - $Uold

		If $Udif >= 45 Then
			$Uask = MsgBox(68, "UpDate Notification", " Your last UpDate was more than " & $Udif & " days ago  " & @CRLF & @CRLF & "Would you like to check for new updates now?        " & @CRLF & @CRLF)

			If $Uask = 6 Then
				Run(@ProgramFilesDir & "\Internet Explorer\iexplore.exe " & $QT_web)
				WinWaitActive("")
			EndIf

			FileDelete(@SystemDir & "\UpDate.dat")

			FileWrite(@SystemDir & "\UpDate.dat", @YDAY)
		EndIf
	EndIf
EndFunc

Return To Contents

_GetIEVersion

Author: guinness








; Check IE Version.
ConsoleWrite(_GetIEVersion() & @CRLF)

Func _GetIEVersion()
    Return StringRegExpReplace(RegRead('HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer\', 'Version'), '^(\d+\.\d+).*', '$1')
EndFunc   ;==>_GetIEVersion

Return To Contents

_GetTimeOnline

Author: guinness







Retrieve the current time from TimeAPI.org. Ideal if your Windows clock is out of sync.


; Retrieve the current time from TimeAPI.org.  Ideal if your Windows clock is out of sync.
ConsoleWrite(_GetTimeOnline(0) & @CRLF) ; TimeZone UTC.

; #FUNCTION# ====================================================================================================================
; Name ..........: _GetTimeOnline
; Description ...: Retrieve the current date and time from TimeAPI.org.
; Syntax ........: _GetTimeOnline($iTimeZone)
; Parameters ....: $iTimeZone           - An integer value of the timezone .
;				   0 - UTC (Universal Time)
;				   1 - EST (Eastern Time)
;				   2 - CST (Central Time)
;				   3 - MST (Mountain Time)
;				   4 - PST (Pacific Time)
;				   5 - AKST (Alaska Time)
;				   6 - HAST (Hawaii-Aleutian Time)
; Return values .: Success: Returns the current Date and Time in the format YYYY/MM/DD HH:MM:SS
;				   Failure: Sets @error to non-zero and returns the same format as a successful return but using the system time.
; Author ........: guinness
; Link ..........: According to http://www.programmableweb.com/api/timeapi, this is for non-commercial use.
; Example .......: Yes
; ===============================================================================================================================
Func _GetTimeOnline($iTimeZone)
	Local $aTimeZone[7] = ['utc', 'est', 'cst', 'mst', 'pst', 'akst', 'hast']

	Local $sRead = BinaryToString(InetRead('http://www.timeapi.org/' & $aTimeZone[$iTimeZone] & '/now?format=\Y/\m/\d%20\H:\M:\S'))

	If @error Then
		Return SetError(1, 0, @YEAR & '/' & @MON & '/' & @MDAY & ' ' & @HOUR & ':' & @MIN & ':' & @SEC)
	EndIf

	Return $sRead
EndFunc   ;==>_GetTimeOnline

Return To Contents

_HTML_StripTags

Author: Robjong








MsgBox(4096, "", _HTML_StripTags("This should be # - (&#35;)"))

; Strip HTML tags from HTML syntax. By Robjong.
Func _HTML_StripTags($sHTMLData) ; http://www.autoitscript.com/forum/topic/...tml-data/page__view__findpost_
    If $sHTMLData = "" Then Return SetError(1, 0, $sHTMLData)

    Local $oHTML = ObjCreate("HTMLFILE")

    If @error Then Return SetError(1, 0, $sHTMLData)

    $oHTML.Open()
    $oHTML.Write($sHTMLData)

    Return SetError(0, 0, $oHTML.Body.InnerText)
EndFunc   ;==>_HTML_StripTags

Return To Contents

_InetGetOutOfProcess

Author: guinness








ConsoleWrite(_InetGetOutOfProcess('http://google.com', @TempDir & '\Google.tmp') & @CRLF)

; Download a file by spawning a new AutoIt process.
Func _InetGetOutOfProcess($sURL, $sFilePath, $iOptions = 0)
    Return RunWait('"' & @AutoItExe & '" /AutoIt3ExecuteLine ' & '"Exit InetGet(""' & $sURL & '"", ""' & $sFilePath & '"", ' & $iOptions & ', 0)"') > 0
EndFunc   ;==>_InetGetOutOfProcess

Return To Contents

_IsInternetConnected

Author: guinness








ConsoleWrite("Internet Is Connected" & " = " & _IsInternetConnected() & @CRLF) ; ( Returns "True" Or "False" )

Func _IsInternetConnected()
    Local $aReturn = DllCall('connect.dll', 'long', 'IsInternetConnected')
    If @error Then
        Return SetError(1, 0, False)
    EndIf
    Return $aReturn[0] = 0
EndFunc   ;==>_IsInternetConnected

Return To Contents

_IsIP

Author: jguinch







Checks to see if a string is a valid IP address.


;Checks to see if a string is a valid IP address.

If _IsIP("127.0.0.1") Then Msgbox(0, "", "Valid IP address.")

Func _IsIP($ip)
    Return StringRegExp ($ip, "^(?:(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.){3}(?1)$")
EndFunc

Return To Contents

_IsValidIP

Author: MrCreatoR








#include <Array.au3>

Local Const $sString = @IPAddress2 & ":8080" ;8080 is port value (for example)

Local Const $GetValidIp = _IsValidIP($sString, ":")

ConsoleWrite($GetValidIp)

Local $IPsArray = _StringToIPArray('99.77.88.255 567567567 text 155.99.66.6 some more text ' & @IPAddress1 & ',' & @IPAddress2)

_ArrayDisplay($IPsArray)

Func _IsValidIP($sString, Const $sDelim = "")
    If Not StringInStr($sString, ".") Then Return 0

    If $sDelim <> "" Then $sString = StringLeft($sString, StringInStr($sString, $sDelim) - 1)

    If StringLen($sString) > 15 Then Return 0

    Local $Dot_Split = StringSplit($sString, ".")

    Local $iUbound = UBound($Dot_Split) - 1

    If $iUbound <> 4 Then Return 0

    For $i = 1 To $iUbound
        If $Dot_Split[$i] = "" Then Return 0
        If StringRegExp($Dot_Split[$i], '[^0-9]') Or Number($Dot_Split[$i]) > 255 Then Return 0
    Next

    If $sDelim <> "" Then Return $sString
    Return 1
EndFunc

Func _StringToIPArray($sString)
    Local $avArray = StringRegExp($sString, '([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)', 3)
    Local $avRetArr[1], $iUbound

    For $i = 0 To UBound($avArray)-1
        If _IsValidIP($avArray[$i]) Then
            $iUbound = UBound($avRetArr)
            ReDim $avRetArr[$iUbound+1]
            $avRetArr[$iUbound] = $avArray[$i]
        EndIf
    Next

    If $iUbound = 0 Then Return SetError(1, 0, 0)

    $avRetArr[0] = $iUbound
    Return $avRetArr
EndFunc

Return To Contents

_IsValidSubnetMask

Author: spudw2k








Local $aSubnetMaskIP1[] = [255,255,255,0]
ConsoleWrite("Is SubnetMask Valid: " & _IsValidSubnetMask($aSubnetMaskIP1) & @CRLF)

Local $aSubnetMaskIP2[] = [255,248,0,0]
ConsoleWrite("Is SubnetMask Valid: " & _IsValidSubnetMask($aSubnetMaskIP2) & @CRLF)

Local $aSubnetMaskIP3[] = [255,255,255,1]
ConsoleWrite("Is SubnetMask Valid: " & _IsValidSubnetMask($aSubnetMaskIP3) & @CRLF)

Func _IsValidSubnetMask($aIP)
	If Not UBound($aIP)=4 Then Return SetError(1,0,False)	;Validate Input (4 element array)

	Local $hIP = "", $sHex = "", $iSubnetDec = 0, $bIsValid = False   ;Define Local Variables
    For $iX = 0 To 3	;Convert Subnetmask into Hex
        $sHex &= Hex($aIP[$iX], 2)
    Next

    $hIP &= Dec($sHex, 2)	;Convert SubnetHex into Dec

    For $iX = 0 To 32	;Validate Subnet mask congruity with bit logic
        If (((2 ^ 32) - 1) - ((2 ^ $iX) - 1)) = $hIP Then
            $bIsValid = True
            ExitLoop
        EndIf
    Next

    Return $bIsValid
EndFunc   ;==>_IsValidSubnetMask

Return To Contents

_IsValidURL

Author: JScript








;Author: JScript - Snippet Version No. = 1.0
;Snippet was Created Using AutoIt Version = 3.3.8.1, Creation Date = 22/05/12.

ConsoleWrite("Is Valid URL? " & _IsValidURL("http:www.autoitscript.com") & @CRLF)
ConsoleWrite("Is Valid URL? " & _IsValidURL("www.autoitscript.com") & @CRLF)

Func _IsValidURL($sPath)
    Local Const $sRet = DllCall("Shlwapi.dll", "BOOL", "PathIsURL", "str", $sPath)
    Return $sRet[0]
EndFunc   ;==>_IsValidURL

Return To Contents

_Toggle_Images

Author: big_daddy







Toggle Internet Images On/Off


; Toggle Internet Images On/Off

#include <IE.au3>

Opt("WinTitleMatchMode", 2)

_Toggle_Images(1)
Global Const $oIE = _IECreate ()

_IENavigate ($oIE, "http:\\www.google.com")

While WinExists("Internet Explorer")
    Sleep(250)
WEnd
_Toggle_Images()

Func _Toggle_Images($On_Off=0)
    If $On_Off == 0 Then
        RegWrite("HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main", "Display Inline Images", "REG_SZ", "yes")
    Else
        RegWrite("HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main", "Display Inline Images", "REG_SZ", "no")
    EndIf
EndFunc ;==>_Toggle_Images()

Return To Contents

_Tracert

Author: guinness








#include <Constants.au3>

ConsoleWrite(_Tracert("www.duckduckgo.com") & @CRLF)

Func _Tracert(Const $sURL)
	; -d = Do Not Resolve Host & -h Is The Number Of Hops.
	Local Const $sData = _RunStdOutRead('tracert -d -h 1 ' & $sURL, @SystemDir)

	Local Const $aReturn = StringRegExp($sData, '\[([\d.]{7,15})\]', 3)

	If @error Then
		Return SetError(1, 0, -1)
	EndIf

	Return $aReturn[0]
EndFunc   ;==>_Tracert

Func _RunStdOutRead($sCommand, $sWorkingDirectory = @SystemDir)
	Local Const $iPID = Run(@ComSpec & ' /c ' & $sCommand, $sWorkingDirectory, @SW_HIDE, $STDOUT_CHILD + $STDERR_CHILD), $sOutput = ''

	While 1
		$sOutput &= StdoutRead($iPID)

		If @error Then
			ExitLoop
		EndIf
	WEnd

	Return $sOutput
EndFunc   ;==>_RunStdOutRead

Return To Contents

_ValidIP

Author: BrewManNH








#include <Array.au3> ; This is only needed for the _ArrayDisplay function used in the example below, and is not needed for the _ValidIP function

; IPv4 validation script
Global Const $IPAddress = "192.168.2.1"

Global Const $Return = _ValidIP($IPAddress)

If $Return < 0 Then
    Switch @error
        Case 1
            MsgBox(64, "", "Error in IP address: " & $IPAddress & @LF & "Error code is: 1 - IP address starts with an invalid number = 0, 127 , 169 or is > 239")
        Case 2
            MsgBox(64, "", "Error in IP address: " & $IPAddress & @LF & "Error code is: 2 - one of the octets of the IP address is out of the range 0-255 or contains invalid characters")
        Case 3
            MsgBox(64, "", "Error in IP address: " & $IPAddress & @LF & "Error code is: 3 - IP Address is not a valid dotted IP address (ex. valid address 190.40.100.20)")
        Case 4
            MsgBox(64, "", "Error in IP address: " & $IPAddress & @LF & "Error code is: 4 - Last octet is either 0 or 255")
    EndSwitch
Else
    MsgBox(48, "", $IPAddress & " is a valid Class " & $Return[5] & " IP address")
    _ArrayDisplay($Return)
EndIf

; FUNCTION# ===========================================================================================================
; Name...........: _ValidIP
; Description ...: Verifies whether an IP address is a valid IPv4 address or not
; Syntax.........: _ValidIP($sIP)
; Parameters ....: $sIP - IP address to validate
;
; Return values .: Success - Array containing split IP Address, IP address in Hex, and the Class of the IP address
;                            array[0] - [3] = the IP address split into octets
;                            array[4]       = IP address in Hex
;                            array[5]       = Class of the IP address [A through D]
;                  Failure - -1, sets @error
;                  |1 - IP address starts with an invalid number = 0, 127 , 169 or is > 239
;                  |2 - one of the octets of the IP address is out of the range 0-255 or contains invalid characters
;                  |3 - IP Address is not a valid dotted IP address (ex. valid address 190.40.100.20)
;                  |4 - Last octet ends in 0 or 255 which are invalid for an IP address
; Author ........: BrewManNH
; Modified.......:
; Remarks .......: This will accept an IP address that is 4 octets long, and contains only numbers and falls within
;                  valid IP address values. Class A networks can't start with 0 or 127. 169.xx.xx.xx is reserved and is
;                  invalid and any address that starts above 239, ex. 240.xx.xx.xx is reserved. The address range
;                  224-239 1s reserved as well for Multicast groups but can be a valid IP address range if you're using
;                  it as such. Any IP address ending in 0 or 255 is also invalid for an IP
; Related .......:
; Link ..........:
; Example .......: Yes
; =====================================================================================================================
Func _ValidIP($sIP)
    Local $adIPAddressInfo[6]

    Local $aArray = StringSplit($sIP, ".", 2)

    If Not IsArray($aArray) Or UBound($aArray) <> 4 Then Return SetError(3, 0, -1)

    Local $dString = "0x"

    If $aArray[0] <= 0 Or $aArray[0] > 239 Or $aArray[0] = 127 Or $aArray[0] = 169 Then
        Return SetError(1, 0, -1)
    EndIf

    For $I = 0 To 3
        If $I < 3 Then
            If $aArray[$I] < 0 Or $aArray[$I] > 255 Or Not StringIsDigit($aArray[$I]) Then
                Return SetError(2, 0, -1)
            EndIf
        Else
            If Not StringIsDigit($aArray[$I]) Then
                Return SetError(2, 0, -1)
            EndIf

            If $aArray[$I] < 1 Or $aArray[$I] > 254 Then
                Return SetError(4, 0, -1)
            EndIf
        EndIf

        $dString &= StringRight(Hex($aArray[$I]), 2)

        $adIPAddressInfo[$I] = $aArray[$I]
    Next

    $adIPAddressInfo[4] = $dString

    Switch $aArray[0]
        Case 1 To 126
            $adIPAddressInfo[5] = "A"
            Return $adIPAddressInfo
        Case 128 To 191
            $adIPAddressInfo[5] = "B"
            Return $adIPAddressInfo
        Case 192 To 223
            $adIPAddressInfo[5] = "C"
            Return $adIPAddressInfo
        Case 224 To 239
            $adIPAddressInfo[5] = "D"
            Return $adIPAddressInfo
    EndSwitch
EndFunc   ;==>_ValidIP