Determining if you or your application is connected to the internet may sound like an easy task – But it really wasn’t as easy as it sounds for me when i was trying to figure a way out to find a way to know if my computer is connected to the internet using VB.net / Visual Basic 2005. I have done quite a search on this… In my search results, I have only seen people praising to use the wininet.dll API, I do not know why people even bothered to post useless code like that, it really does not work! However, I think I may be wrong – people with different types of internet connection might see different results, so it is completely up to you – If you have not tried that out already you should do so now. You never know, maybe it might help in your situation – but from what I have been hearing that the wininet.dll API is not that reliable. The two working solutions I found so far: The first method is to ping a host (which is the most common):
Function IsConnected() As Boolean Return My.Computer.Network.Ping("188.8.131.52") End Function
I recommend using IP Address (127.0.0.1) instead of a hostname (like www.google.com). When you do use this method you have to be all the time – for instance (www.google.com) or (www.microsoft.com) is very less likely to go down. The second method is my personal, which I thought was more reliable atleast in my case.
Function IsConnected() As Boolean Try My.Computer.Network.DownloadFile("http://www.google.com/abc.txt", "app_tool.dll", "", "", True, 100, True) If My.Computer.FileSystem.GetFileInfo("app_tool.dll").Length > 1 Then Return True End If Catch Return False End Try End Function
This function downloads a file from a reliable source that is always online like (www.google.com) and (www.microsoft.com) – if the download is successful we go further and check the length. We use My.Computer.Network.DownloadFile to download the file, we pass some special parameters to it like the complete URL to the file we want to download and then the filename we want to give it after its copied to our hard-drive. We can also pass values such as a username and password (I have these set to an empty string like this “” with two double quotes). One of the useful parameter is if or not we want to show the end user a UI (User Interface) showing that a file is being downloaded to their computer, This is a boolean value True or False. Then there is the second last parameter Timeout which takes an integer as a value (Timeout is set to 100 seconds by default) and last but not least is the overwrite parameter which is to tell weather or not we want to overwrite the file, we can set that to either true or false. There is another method but I wont be discussing about that since it didn’t work quite correctly but I have been seeing people post messages alot that it is the best method – which is using a System.Net.WebRequest, But before you go let me also tell you that this method is also alot slower than the above.