Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

[Solved] Check if connected to the Internet


  • Please log in to reply
13 replies to this topic
Bruttosozialprodukt
  • Members
  • 457 posts
  • Last active: Oct 18 2015 08:47 AM
  • Joined: 20 Oct 2012

I'm looking for a function that checks if a computer has access to the Internet. 

I was thinking about pinging a huge backbone or DNS server. 

Has anyone already written something like this? Or do you have any suggestions?



GEV
  • Members
  • 1364 posts
  • Last active: Dec 05 2018 06:05 PM
  • Joined: 23 Oct 2013
ConnectedToInternet(flag=0x40) { 
Return DllCall("Wininet.dll\InternetGetConnectedState", "Str", flag,"Int",0) 
}

If ConnectedToInternet()
MsgBox Connected!

http://www.autohotke...nection-status/



flyingDman
  • Spam Officer
  • 2186 posts
  • Last active: Nov 07 2015 08:15 AM
  • Joined: 27 Feb 2009

We have had a similar post recently and the comment was made that ConnectedToInternet does not check whether there is indeed a connection but merely if the cable is plugged in.  So pinging is probably the safest to determine whether there's a true connection.  See if you can use something like this:

msgbox % checknet()
msgbox % checknet(x) ? "good connection" : "poor or no connection"
msgbox % x

checknet(ByRef verb:=""){
Runwait %comspec% /c ping google.com | clip,,hide
regexmatch(gp := clipboard,"Lost = (\d+)",oVar1)
Runwait %comspec% /c ping yahoo.com | clip,,hide
regexmatch(yp := clipboard,"Lost = (\d+)",oVar2)
verb := gp "`n" yp
return ovar11 + ovar21 = 0 ? 1:0
}

Note: this requires clip.exe to be on your machine (avoids having to pipe it into a file)


Marine Corps Gen. Joseph Dunford told senators at his Joint Chiefs of Staff confirmation hearing : “If you want to talk about a nation that could pose an existential threat to the United States, I'd have to point to Russia. And if you look at their behavior, it's nothing short of alarming.”


Bruttosozialprodukt
  • Members
  • 457 posts
  • Last active: Oct 18 2015 08:47 AM
  • Joined: 20 Oct 2012

Well, yeah we would of course have to ping anything on the Internet. 
I did some research and there are 13 so called "root name servers". Basically without them we couldn't access any domain anymore...
 
So I ended up with this:

MsgBox % Connected()

#Include Ping.ahk ;http://www.autohotkey.com/board/topic/87742-simpleping-successor-of-ping/ ;You might wanna replace all the "throw Exception(.....)" lines with Return False
Connected() {
    Static RootNameServers = ["198.41.0.4","192.228.79.201","192.33.4.12","199.7.91.13","192.203.230.10","192.5.5.241","192.112.36.4","128.63.2.53","192.36.148.17","192.58.128.30","193.0.14.129","199.7.83.42","202.12.27.33"]
    Loop % RootNameServers.MaxIndex()
    If (Ping(RootNameServers[A_Index]))
        Return True
    Return False
}

edit: fixed the code



Bruttosozialprodukt
  • Members
  • 457 posts
  • Last active: Oct 18 2015 08:47 AM
  • Joined: 20 Oct 2012

I'm having some weird issues with the code that I posted above.

For some reason it keeps returning true, even though I'm not connected anymore.

Is there some kind of cache that is screwing with the ping results?



bruno
  • Members
  • 635 posts
  • Last active: Nov 04 2015 02:26 PM
  • Joined: 07 Mar 2011

how about this?: ;)

; NetMeter
; http://www.autohotkey.com/forum/topic18033-15.html

/*
Notes:

- The Gui displays Bytes Sent/Received, KB/s, and Total MB.
- An Icon on the Gui as well as the tray Icon reflects the status.
- Double click the Tray icon to Show/Hide the GUI.
- Right click on the GUI to display the Tray menu.
- Drag and locate the GUI to the desired position. The Location will be remembered.
- Dynamic polling. Polls per 256ms during activity, per 1024ms when inactive.
- Less GUI flicker.
*/

#SingleInstance, Force
DetectHiddenWindows, OFF ; OFF is default, but this script would err if set ON

Menu, Tray, NoStandard
Menu, Tray, Add, Show/Hide, ShowHide
Menu, Tray, Add
Menu, Tray, Standard
Menu, Tray, Default, Show/Hide
Menu, Tray, Icon, NetShell.dll, 58

IfNotExist, %A_Temp%\NetStatus.bmp
UrlDownloadToFile, http://www.autohotkey.net/~goyyah/samples/grad001.bmp
, %A_Temp%\NetStatus.bmp

Gui -Caption +Border +ToolWindow +AlwaysOnTop +LastFound
GuiID := WinExist() , prv_iNo := 44
Gui, Color , FFFFEE
Gui, Margin, 0, 0
Gui, Font  , s8, Verdana
Gui, Add, Picture, x40   y0   w200 h40 vConn  GuiMove, %A_Temp%\NetStatus.bmp
Gui, Add, Picture, x5    y6     Icon30 vIcon  GuiMove, NetShell.dll
Gui, Add, Text   , x+7   y3    w75  h16 +Border
Gui, Add, Text   , xp+1  yp+1  w70  h14 +0x200 c5B0000 +Right  HWNDSent
Gui, Add, Text   , xp-1  y+3   w75  h16 +Border
Gui, Add, Text   , xp+1  yp+1  w70  h14 +0x200 c5B0000 +Right  HWNDRecv
Gui, Add, Text   , x+7   y3    w80  h16 +Border   
Gui, Add, Text   , xp+4  yp+1  w75  h14 c003D00                HWNDkbps 
Gui, Font, Bold
Gui, Add, Text   , xp-4  y+3   w80  h16 +Border
Gui, Add, Text   , xp+4  yp+1  w75  h14 c003D00                HWNDband 

IniRead, X, %A_Temp%\%A_ScriptName%.INI, GuiPos, XPos, 20
IniRead, Y, %A_Temp%\%A_ScriptName%.INI, GuiPos, YPos, 20

Gui, Show, x%x% y%y% w205 h40, NetMeter

If GetIfTable(tb)
   ExitApp

Loop, % DecodeInteger(&tb) {
   If DecodeInteger(&tb + 4 + 860 * (A_Index - 1) + 544) < 4
   || DecodeInteger(&tb + 4 + 860 * (A_Index - 1) + 516) = 24
      Continue

   ptr := &tb + 4 + 860 * (A_Index - 1)
      Break
                           }
IfLess, ptr, 1, ExitApp
SetTimer, NetMeter

Return ; AutoExecute Section ends

NetMeter:
   SetTimer, NetMeter, Off
   DllCall("iphlpapi\GetIfEntry", "Uint", ptr)

   dnNew := DecodeInteger(ptr + 552)   ,    upNew  := DecodeInteger(ptr + 576)     
   dnRate := Round((dnNew - dnOld) )   ,    upRate := Round((upNew - upOld) )
   PollMs := (dnRate - upRate = 0) ? 1024 : 256

   Menu, Tray, Tip, % "Sent: " upNew " / Recv: " dnNew " / Total: "
                  . Round((((upNew+dnNew) /1024)/1024),1) . " MB"

   ; Determine & update GUI-Icon & Tray-Icon
   IfGreater,dnRate,0,  IfGreater,upRate,0,  SetEnv,iNo,41     ;  Recv/Sent
   IfGreater,dnRate,0,  IfEqual  ,upRate,0,  SetEnv,iNo,42     ;  Recv
   IfEqual  ,dnRate,0,  IfGreater,upRate,0,  SetEnv,iNo,43     ;  Sent
   IfEqual  ,dnRate,0,  IfEqual  ,upRate,0,  SetEnv,iNo,44     ;  None
   IfNotEqual,iNo, %prv_iNo%,  Menu, Tray, Icon, NetShell.dll, % iNo+14

   If WinExist( "ahk_id " . GuiID )  {                ; Update the GUI Data
   ControlSetText,, %upNew%                                         , ahk_id %Sent%   
   ControlSetText,, %dnNew%                                         , ahk_id %Recv%
   ControlSetText,, % Round((dnrate+uprate)/PollMs) . " KBps"       , ahk_id %Kbps%
   ControlSetText,, % Round((((upNew+dnNew) /1024)/1024),1) . " MB" , ahk_id %Band%
   IfNotEqual,iNo, %prv_iNo%,  GuiControl,, Icon, *Icon%iNo% NetShell.dll
                                     }

   prv_iNo := iNo , dnOld := dnNew , upOld := upNew
   SetTimer, NetMeter, %PollMs%
Return

uiMove:
   PostMessage, 0xA1, 2,,, A
   Sleep 200
   WinGetPos, X, Y
   IniWrite, %X%, %A_Temp%\%A_ScriptName%.INI, GuiPos, XPos
   IniWrite, %Y%, %A_Temp%\%A_ScriptName%.INI, GuiPos, YPos
Return

ShowHide:
   GuiControl,, Icon, *Icon%iNo% NetShell.dll
   IfWinExist, ahk_id %GuiID%,,,, WinHide, ahk_id %GuiID%
   Else                           WinShow, ahk_id %GuiID%
Return

GuiContextMenu:
   Menu, Tray, Show
Return

GetIfTable(ByRef tb, bOrder = False) {
   nSize := 4 + 860 * GetNumberOfInterfaces() + 8
   VarSetCapacity(tb, nSize)
   Return DllCall("iphlpapi\GetIfTable", "Uint", &tb, "UintP", nSize, "int", bOrder)
                                     }

GetIfEntry(ByRef tb, idx)            {
   VarSetCapacity(tb, 860)
   DllCall("ntdll\RtlFillMemoryUlong", "Uint", &tb + 512, "Uint", 4, "Uint", idx)
   Return DllCall("iphlpapi\GetIfEntry", "Uint", &tb)
                                     }

GetNumberOfInterfaces()              {
   DllCall("iphlpapi\GetNumberOfInterfaces", "UintP", nIf)
   Return nIf
                                     }

DecodeInteger(ptr)                   {
   Return *ptr | *++ptr << 8 | *++ptr << 16 | *++ptr << 24
                                     }


Oldman
  • Members
  • 2475 posts
  • Last active: Feb 18 2015 04:57 PM
  • Joined: 01 Dec 2013

I use 'InternetCheckConnection' from the Windows API.
On internet, people say it is not reliable. in some old forum topics.
Microsoft did some changes in the Dll, since then.

 

Maybe it became a sort of Urban legend.

 

I tested the Ping on 'http://Autohotkey.com' without success, while it succeed with the 'InternetCheckConnection' function.

I also tested with valid and invalid addresses with success.

 

InternetCheckConnection.7z.


Si ton labeur est dur et que tes résultats sont minces, souviens toi du grand chêne qui avant n'était qu'un gland....comme toi ! (anonyme) ;)

L'art de lire, c'est l'art de penser avec un peu d'aide. (É. Faguet)

Windows 3.1. Collector's Edition.     (www.avaaz.org)


girlgamer
  • Moderators
  • 3263 posts
  • Last active: Feb 01 2015 09:49 AM
  • Joined: 04 Jun 2010
Call me crazy but why not just do an internet speed test like to http://www.speedtest.net/?test-2
with an empty clipboard. hit the test button. wait an appropriate period of time. Click on where
the copy button would be and then check the clipboard to see if you got a result?
http://www.speedtest...sult/3702630064 ;<-- this one shows I'm connected.
you shouldn't get anything like this if you aren't connected.

The universe is a wondrous place! The faster you create unbreakable code, the faster the universe creates people that can break it. All scripting follows the rule Rule Of Twos -- 1) Good, 2) Fast 3) Cheap -- pick any Two.
I guarantee absolutely nothing about any code I provide except that it works in my machine. ●
MMO Fighter   KeyLooperDemo   Key Spammer   TinyClickRecorder  GGs Password Generator.ahk
For the newest version of AutoHotkey and some killer scripts go here.
Rock-on%20kitten.gif


bruno
  • Members
  • 635 posts
  • Last active: Nov 04 2015 02:26 PM
  • Joined: 07 Mar 2011

AT&T U-verse recommends http://speakeasy.net/speedtest/. ;)



girlgamer
  • Moderators
  • 3263 posts
  • Last active: Feb 01 2015 09:49 AM
  • Joined: 04 Jun 2010
Whatever works is whatever works as long as you can get something back that shows you hit the connection. I just picked this off
the top of what's left of my head.

The universe is a wondrous place! The faster you create unbreakable code, the faster the universe creates people that can break it. All scripting follows the rule Rule Of Twos -- 1) Good, 2) Fast 3) Cheap -- pick any Two.
I guarantee absolutely nothing about any code I provide except that it works in my machine. ●
MMO Fighter   KeyLooperDemo   Key Spammer   TinyClickRecorder  GGs Password Generator.ahk
For the newest version of AutoHotkey and some killer scripts go here.
Rock-on%20kitten.gif


Bruttosozialprodukt
  • Members
  • 457 posts
  • Last active: Oct 18 2015 08:47 AM
  • Joined: 20 Oct 2012

@bruno I'm looking for a function to check if a computer is connected to the Internet, not for a script that shows my down/upload rate (I already have NetSpeedMonitor btw).

@Oldman It didn't work for me. Try to unplug the dsl cable from your router (not the one that connects your PC with the router), then start the script. It doesn't really check if you are connected to the Internet, I guess it only checks if you are connected to a router or a network in general...

@girlgamer As I said to bruno, I'm not looking for a speed test or whatever. I'm looking for a very fast and 100% reliable function that checks if I'm connected to the Internet. I don't want to rely on some random website that will probably think that I'm DoSing it when I keep pinging it.

 

I think my idea of pinging all the root name servers is pretty good and probably the most reliable way of checking your Internet connection.

I just need to get it to work. And I mean it kinda does work... But I was calling the function every 400 milliseconds or so and after a while it just kept returning the same ping results over and over again no matter if my router had a connection or not.



Bruttosozialprodukt
  • Members
  • 457 posts
  • Last active: Oct 18 2015 08:47 AM
  • Joined: 20 Oct 2012

And I'm still looking for a fast and 100% reliable way of finding out if there is an Internet connection.

An http request (or using an actual browser) is completely overkill, unreliable, extremely inefficient and very slow, not to mention that a random Internet site is likely not very reliable.
As I said, it will probably detect your requests as spam / DoS and will ban you after a while, it's also not very nice to spam requests to any site in general... 

That's why I came up with pinging the root name servers.

 

Btw I managed to more or less reproduce the issue that I'm having.

Run the connection function in a loop then disable your network adaptor. Wait some seconds, then enable it again, then wait again, then disable it again. For me the connection function still returns true at this point, while it didn't when I disable the adaptor for the first time.



ahcahc
  • Members
  • 129 posts
  • Last active: Sep 24 2016 08:15 AM
  • Joined: 21 Jun 2012

This is what I do to check for internet connection.

html := UrlDownloadToVar("http://www.google.com")
if html
    MsgBox connected to the internet
UrlDownloadToVar(URL) {
ComObjError(false)
WebRequest := ComObjCreate("WinHttp.WinHttpRequest.5.1")
WebRequest.Open("GET", URL)
WebRequest.Send()
Return WebRequest.ResponseText
}


Linear Spoon
  • Members
  • 842 posts
  • Last active: Sep 29 2015 03:56 AM
  • Joined: 29 Oct 2011

You seem to be asking for a function that knows if there is a path to "the internet", without actually traversing the path. Your computer only knows what is directly connected to its network interfaces...anything else it has to test, and that can be slow.

 

This is how Microsoft recommends applications be network aware. There is a lot of COM magic here, so I have don't really have an interest in translating an example.

http://msdn.microsof...1(v=VS.85).aspx

 

This is supposedly how Vista and Win 7 check internet connectivity.

http://technet.micro...5(v=WS.10).aspx

 

This is my attempt at reproducing the second link. Most runs took 80-200ms, with one outlier at 2.2 seconds (perhaps the server was busy). In addition, once Windows itself noticed the connection was down, GetAddrInfoW seems to fail immediately, leading to a result in less than 10ms. This has worked correctly for every case I tried.

;Should be compatible with Win XP or higher, 32/64 bit, Unicode or ANSI, latest version.
IsInternetConnected()
{
  static sz := A_IsUnicode ? 408 : 204, addrToStr := "Ws2_32\WSAAddressToString" (A_IsUnicode ? "W" : "A")
  VarSetCapacity(wsaData, 408)
  if DllCall("Ws2_32\WSAStartup", "UShort", 0x0202, "Ptr", &wsaData)
    return false
  if DllCall("Ws2_32\GetAddrInfoW", "wstr", "dns.msftncsi.com", "wstr", "http", "ptr", 0, "ptr*", results)
  {
    DllCall("Ws2_32\WSACleanup")
    return false
  }
  ai_family := NumGet(results+4, 0, "int")    ;address family (ipv4 or ipv6)
  ai_addr := Numget(results+16, 2*A_PtrSize, "ptr")   ;binary ip address
  ai_addrlen := Numget(results+16, 0, "ptr")   ;length of ip
  DllCall(addrToStr, "ptr", ai_addr, "uint", ai_addrlen, "ptr", 0, "str", wsaData, "uint*", 204)
  DllCall("Ws2_32\FreeAddrInfoW", "ptr", results)
  DllCall("Ws2_32\WSACleanup")
  http := ComObjCreate("WinHttp.WinHttpRequest.5.1")

  if (ai_family = 2 && wsaData = "131.107.255.255:80")
  {
    http.Open("GET", "http://www.msftncsi.com/ncsi.txt")
  }
  else if (ai_family = 23 && wsaData = "[fd3e:4f5a:5b81::1]:80")
  {
    http.Open("GET", "http://ipv6.msftncsi.com/ncsi.txt")
  }
  else
  {
    return false
  }
  http.Send()
  return (http.ResponseText = "Microsoft NCSI") ;ncsi.txt will contain exactly this text
}

Join us at the new forum - http://www.ahkscript.org/