Jump to content

Network detection


Recommended Posts

For many scripts there are dependencies such as installed apps, dlls, and whatever. If one script is developed say like Spybot S&D installer that requires internet connection to complete because of options chosen for the installer or many other scripts like it then it is wise to verify the internet connection as a prerequisite prior to entering the installer.

I had a little trouble when I first encountered the need for this, but overcame it with a simple "ping" using the built in Windows ping.exe instead of AutoIts Ping() function and then parsing the logfile to verify connected or not. I realize that dependency on ping isn't always the best choice, but at that time that is all I could wrap my head around.

When the many flavors of Windows Vista were released I ran into one of the strangest problems that I still cannot find the cause, nor care much about anymore. Sometimes ping would fail without returning any value on some Vista machines. Because of that I had to search for another means of network detection that involved use of netsh. Even then this was not always conclusive and I then took a simple path to look an IP addresses and verified not 127.0.0.1 or self assigned. I haven't had enough experience with Windows 7 and my scripts, but they have been reported to me as functional. I assumed they would since Windows 7 really isn't "7", but rather major version 6 which really is just candied up Vista.

The functions that I wrote then to detect network connection currently:

Func networkDetectedPingMethod()
    $bIpAddressAlive = False
    TrayTip("Detecting Network", "Using ping method. ", 60)
    RunWait(@ComSpec & " /c ping.exe www.google.com>""%TEMP%/pingResults.log""", @SystemDir, @SW_HIDE)
    Sleep(500)
    ;parse pingResults.log for not 100% loss
    If FileExists(@TempDir & "/pingResults.log") Then
        $ipFile = FileOpen(@TempDir & "/pingResults.log", 0)

        If $ipFile == -1 Then
            ;message to master log file with error
            MsgBox(0, "pingResultsLog missing", "Pete must have made a mistake in coding.  Can't find the log file to parse.")
        Else
            While 1
                $line = FileReadLine($ipFile)
                If @error == -1 Then ExitLoop
                If StringInStr($line, "Request timed out") Or StringInStr($line, "Ping request could not find host") Then
                    $bIpAddressAlive = False
                    TrayTip("","",0)
                    ExitLoop
                Else
                    $bIpAddressAlive = True
                EndIf
            WEnd
        EndIf
        FileClose($ipFile)
        Sleep(500)
    EndIf
    TrayTip("","",0)
    Return $bIpAddressAlive
EndFunc

Func networkDetectedNetshDiagMethod()
    ;I spent hours developing this method only to find that it doesn't work for vista!!!!!!
    $bIpAddressAlive = False
    TrayTip("Detecting Network", "Using network shell diagnostics.", 60)
    RunWait(@ComSpec & " /c netsh diag connect iphost google.com 80>""%TEMP%/netshDiagConnectIphost.log""", @SystemDir, @SW_HIDE)
    Sleep(500)
    ;parse netshDiagConnectIphost.log for connection to port 80
    If FileExists(@TempDir & "/netshDiagConnectIphost.log") Then
        $ipFile = FileOpen(@TempDir & "/netshDiagConnectIphost.log", 0)

        If $ipFile == -1 Then
            ;message to master log file with error
            MsgBox(0, "netshDiagConnectIphost.log missing", "Sn3aky must have made a mistake in coding.  Can't find the log file to parse.")
        Else
            While 1
                $line = FileReadLine($ipFile)
                If @error == -1 Then ExitLoop
                If StringInStr($line, "Server appears to be running on port(s) [NONE]") Then
                    $bIpAddressAlive = False
                    TrayTip("","",0)
                    ExitLoop
                Else
                    $bIpAddressAlive = True
                EndIf
            WEnd
        EndIf
        FileClose($ipFile)
        Sleep(500)
    EndIf
    TrayTip("","",0)
    Return $bIpAddressAlive
EndFunc

Func networkDetectedNetshShowLanInterfaceMethod()
    ;use for vista because VISTA SUCKS!
    $bIpAddressAlive = False
    TrayTip("Detecting Network", "Using network shell diagnostics.", 60)
    RunWait(@ComSpec & " /c netsh lan show interfaces>""%TEMP%/netshLanShowInterface.log""", @SystemDir, @SW_HIDE)
    Sleep(500)
    ;parse netshDiagConnectIphost.log for connection to port 80
    If FileExists(@TempDir & "/netshLanShowInterface.log") Then
        $ipFile = FileOpen(@TempDir & "/netshLanShowInterface.log", 0)

        If $ipFile == -1 Then
            ;message to master log file with error
            MsgBox(0, "netshLanShowInterface.log missing", "Sn3aky must have made a mistake in coding.  Can't find the log file to parse.")
        Else
            While 1
                $line = FileReadLine($ipFile)
                If @error == -1 Then ExitLoop
                If StringInStr($line, "Connected") Then
                    $bIpAddressAlive = True
                    TrayTip("","",0)
                    ExitLoop
                Else
                    If StringInStr($line, "Network cable unplugged") Then MsgBox(0, "Connection not available", "If I had arms I'd do this myself.  Connect me to a wall jack please then hit ok.")
                    $bIpAddressAlive = False
                EndIf
            WEnd
        EndIf
        FileClose($ipFile)
        Sleep(500)
    EndIf
    TrayTip("","",0)
    Return $bIpAddressAlive
EndFunc

Recently I again approached this portion of my script and wasn't satisfied with how ugly and ineffective it was. I checked again into something I faintly remembered seeing in the past. that led me to this snippet of code:

$connect = _GetNetworkConnect()

If $connect Then
    MsgBox(64, "Connections", $connect)
Else
    MsgBox(48, "Warning", "There is no connection")
EndIf

Func _GetNetworkConnect()
    Local Const $NETWORK_ALIVE_LAN = 0x1  ;net card connection
    Local Const $NETWORK_ALIVE_WAN = 0x2  ;RAS (internet) connection
    Local Const $NETWORK_ALIVE_AOL = 0x4  ;AOL
    
    Local $aRet, $iResult
    
    $aRet = DllCall("sensapi.dll", "int", "IsNetworkAlive", "int*", 0)
    
    If BitAND($aRet[1], $NETWORK_ALIVE_LAN) Then $iResult &= "LAN connected" & @LF
    If BitAND($aRet[1], $NETWORK_ALIVE_WAN) Then $iResult &= "WAN connected" & @LF
    If BitAND($aRet[1], $NETWORK_ALIVE_AOL) Then $iResult &= "AOL connected" & @LF
    
    Return $iResult
EndFunc

I've been unable to find documentation on sensapi.dll and I'm having difficulty trying to troubleshoot why this accurately detects a connection, but fails to point out which connection exactly is actually connected. Maybe I'm too much a young pup also to identify what a "RAS" internet connection is. If anyone has knowledge with the last mentioned function or knows where to find documentation on sensapi.dll please let me know. Thanks!

Link to comment
Share on other sites

I use by Yashied. Have a look for either _WinAPI_IsInternetConnected() or _WinAPI_IsNetworkAlive()

Func _Example_2() ; WinAPIEx.au3 Version >> http://www.autoitscript.com/forum/topic/98712-winapiex-udf/    
Local $iNetworkConnected = _WinAPI_IsNetworkAlive() ; I could have used _WinAPI_IsInternetConnected() but this is only available on Windows Vista+ and checks if connection to the Internet is possible too.    
If Not $iNetworkConnected Then $iNetworkConnected = _WinAPI_GetConnectedDlg(1, 1 + 4) ; Run the Connect Wizard if not connected!    
If $iNetworkConnected Then Return 1    
Return SetError(1, 0, $iNetworkConnected)
EndFunc   ;==>_Example_2

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...