How can I detect that there is an internet connection?

How can I detect that there is an internet connection?
Peter Goossens

How can I detect that there is an internet connection?
Peter Goossens
Peter,
You might want to experiment with this. It's not perfect, but...
Class
Imports System.IO
Imports System.Net
Namespace InternetConnection
Public Class SiteInfo
Private _displayName As String
Private _connectionString As String
Private Sub New(ByVal name As String, _
ByVal connectionString As String)
_displayName = name.Trim
_connectionString = connectionString.Trim
End Sub
''' <summary>
''' Gets the connection string of this instance.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public ReadOnly Property ConnectionString() As String
Get
Return _connectionString
End Get
End Property
''' <summary>
''' Gets the display name of this instance.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public ReadOnly Property DisplayName() As String
Get
Return _displayName
End Get
End Property
''' <summary>
''' A method which will add a new site to your collection of SiteInfo.
''' </summary>
''' <param name="siList">Your generic List(Of SiteInfo).</param>
''' <param name="displayName">The display name for this new instance
''' of SiteInfo.</param>
''' <param name="connectionString">The connection string for this
''' new instance of SiteInfo.</param>
''' <remarks></remarks>
Public Shared Sub AddNew(ByRef siList As List(Of SiteInfo), _
ByVal displayName As String, _
ByVal connectionString As String)
Try
If siList Is Nothing Then
Throw New NullReferenceException("The collection of SiteInfo cannot be null.")
ElseIf String.IsNullOrEmpty(displayName) OrElse displayName.Trim = "" Then
Throw New ArgumentException("The display name cannot be null or empty.")
ElseIf String.IsNullOrEmpty(connectionString) OrElse connectionString.Trim = "" Then
Throw New ArgumentException("The connection string cannot be null or empty.")
Else
If siList.Count > 0 Then
Dim findDuplicate As IEnumerable(Of SiteInfo) = _
From si As SiteInfo In siList _
Where si.DisplayName.ToLower.Replace(" "c, "") = _
displayName.ToLower.Replace(" "c, "") AndAlso _
si.ConnectionString.ToLower.Replace(" "c, "") = _
connectionString.ToLower.Replace(" "c, "")
If findDuplicate.Count <> 0 Then
Throw New ArgumentException("This is a duplicate entry.")
Else
siList.Add(New SiteInfo(displayName, connectionString))
End If
Else
siList.Add(New SiteInfo(displayName, connectionString))
End If
End If
Catch ex As Exception
Throw
End Try
End Sub
''' <summary>
''' A method which will return a boolean value to indicate internet
''' connection status.
''' </summary>
''' <param name="siList">Your generic List(Of SiteInfo).</param>
''' <param name="displayName">The display name for the instance
''' of SiteInfo to use.</param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function InternetIsConnected(ByVal siList As List(Of SiteInfo), _
ByVal displayName As String) As Boolean
Dim retVal As Boolean = False
Try
If siList Is Nothing Then
Throw New NullReferenceException("The collection of SiteInfo cannot be null.")
ElseIf siList.Count = 0 Then
Throw New ArgumentOutOfRangeException("Count", "The collection of SiteInfo cannot be empty.")
ElseIf String.IsNullOrEmpty(displayName) OrElse displayName.Trim = "" Then
Throw New ArgumentException("The display name cannot be null or empty.")
Else
Dim findInstance As IEnumerable(Of SiteInfo) = _
From si As SiteInfo In siList _
Where si.DisplayName.ToLower.Replace(" "c, "") = _
displayName.ToLower.Replace(" "c, "")
If findInstance.Count <> 1 Then
Throw New ArgumentException("This instance is not in the collection of SiteInfo.")
Else
retVal = TestConnection(findInstance.First.ConnectionString)
End If
End If
Catch ex As Exception
Throw
End Try
Return retVal
End Function
Private Shared Function TestConnection(ByVal url As String) As Boolean
Dim retVal As Boolean = False
Try
Dim request As WebRequest = WebRequest.Create(url)
Using response As HttpWebResponse = DirectCast(request.GetResponse, HttpWebResponse)
Using dataStream As Stream = response.GetResponseStream
Using reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
retVal = True
End Using
End Using
End Using
Catch ex As WebException
retVal = True
Catch ex As Exception
retVal = False
End Try
Return retVal
End Function
End Class
End Namespace
Example Usage
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
Dim siList As New List(Of InternetConnection.SiteInfo)
InternetConnection.SiteInfo.AddNew(siList, _
"Test1", _
"http://dev.virtualearth.net/REST/v1/Locations/37221?o=xml")
InternetConnection.SiteInfo.AddNew(siList, _
"Test2", _
"nothing here")
InternetConnection.SiteInfo.AddNew(siList, "Test3", _
"www.google.com")
InternetConnection.SiteInfo.AddNew(siList, "Test4", _
"http://fls-online.com")
' This will return true:
Dim bool1 As Boolean = _
InternetConnection.SiteInfo.InternetIsConnected(siList, _
"Test1")
' This will return false:
Dim bool2 As Boolean = _
InternetConnection.SiteInfo.InternetIsConnected(siList, _
"Test2")
' This will return false:
Dim bool3 As Boolean = _
InternetConnection.SiteInfo.InternetIsConnected(siList, _
"Test3")
' This will return true:
Dim bool4 As Boolean = _
InternetConnection.SiteInfo.InternetIsConnected(siList, _
"Test4")
Stop
End Sub
End Class
Let me know your results please?
Still lost in code, just at a little higher level.

Similar Messages

  • Sockets: How can server detect that client is no longer connected?

    Hi,
    I really need help and advice with the following problem:
    I have a Client - Server socket program.
    The server listens on port 30000 using a server socket on one machine
    The client connects to localhost on port 20000, previously creating an ssh port forward connection using the Jsch package from www.jcraft.com with
    "session.setPortForwardingL(20000, addr, 30000);"
    Then the client sends Strings to the server using a PrintWriter.
    Both are connected to each other through the internet and the server uses a dynamic dns service.
    This all works well until the IP address of the Server changes, The client successfully reconnects to the server using the dynamic dns domain name, but the server keeps listening on the old socket from the previous connection, while opening a new one for the new client connection. The server doesn't seem to notice that Client has disconnected because of this IP address change.
    looks like the server is stuck inside the while loop. If i cut the connection manually on the client side, the server seems to notice that the client has disconnected, and jumps out of the while look (see code below)
    this is the code I'm using for the server:
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.Socket;
    import java.util.logging.Logger ;
    public class SocketHandler extends Thread {
        static Logger logger = Logger.getLogger("Server.SocketHandler");
        private Socket clientSocket = null;
        private BufferedReader in = null;
        private InputStreamReader inReader = null;
        public SocketHandler(Socket clientSocket) throws IOException {
            this.clientSocket = clientSocket;
            inReader = new InputStreamReader(clientSocket.getInputStream ());
            in = new BufferedReader(inReader);
        public void run() {
            try {
                String clientMessage = null;
                while ((clientMessage = in.readLine()) != null) {
                    logger.info("client says: " + clientMessage);
            } catch (IOException e) {
                logger.severe(e.getMessage());
                e.printStackTrace();
            } finally {
                try {
                    logger.info("closing client Socket: " + clientSocket);
                    clientSocket.close();
                    in.close();
                    ServerRunner.list.remove(clientSocket);
                    logger.info("currently "+ServerRunner.list.size()+" clients connected");
                } catch (IOException e) {
                    logger.severe (e.getMessage());
                    e.printStackTrace();
    }I've tried making the server create some artificial traffing by writing some byte every few seconds into the clients OutputStream. However I get no exceptions when the IP address changes. The server doesn't detect a disconnected socket connection.
    I'd really appreciate help and advice

    If a TCP/IP peer is shut down "uncleanly", the other end of the connection doesn't get the final end of connection packet, and read() will wait forever. close() sends the final packet, as will killing the peer process (the OS does the close()). But if the OS crashes or for some other reason can't send the final packet, the server never gets notification that the peer has gone away.
    Like you say, one way is timeout, if the protocol is such that there always is something coming in at regular intervals.
    The other way is a heartbeat. Write something to the other end periodically, just some kind of "hello, I'm here, ignore this message". The other end doesn't even have to answer. If the peer has gone away, TCP will retransmit your heartbeat message a few times. After about a minute it will give up, and mark the socket as broken. read() will then throw an IOException. You could send heartbeats from the client too, so that the client detects if the server computer dies.
    TCP/IP also has a TCP-level heartbeat; see Socket.setKeepAlive(). The heartbeat interval is about two hours, so it takes it a while to detect broken connections.

  • If I lost my Iphone, but when I tried to locate with ICloud - find my Iphone it's offline. I lost in another country  which means that there is no Internet connection on my phone. Is there any chance to find?

    If I lost my Iphone, but when I tried to locate with ICloud - find my Iphone it's offline. I lost in another country  which means that there is no Internet connection on my phone. Is there any chance to find?

    In order for a lost iPhone to be located you have to have set 'Find My iPhone' up on it before losing it, and it has to be on, not wiped, and able to connect to a network (how else could it transmit its location) - if any of these conditions is not true then locating it is not possible. You can't use the serial number or IMEI number to locate a phone: the former is only useful to identify it as yours if it turns up, and the latter can be used by most service providers to block it, rendering it useless and preventing anyone from spending your credit.

  • My ipod says that there's no internet connection despite me signed on sky network. what happened? how do i fix it?

    My ipod says that there's not interent connection despite me signed up to SKY network at home! what happened? how do i fix it?

    When you go to Settings>wifi does it show you are connected?
    Do other devices successfully connect to the internet?
    Does the iPod successfully connect to other networks?
    Try:
    - Resetting the iPod. Nothing is lost
    Reset iPod touch: Hold down the On/Off button and the Home button at the same time for at
    least ten seconds, until the Apple logo appears.
    - Power off and then back on the router
    - Reset network settings: Settings>General>Reset>Reset Network Settings
    - iOS: Troubleshooting Wi-Fi networks and connections
    - iOS: Recommended settings for Wi-Fi routers and access points

  • How can I detect that a device is from Motorola !

    hi all !
    I want to detect if my device is a Motorola one, to do so, I was checking the class com.motorola.extensions.ScalableImage, if it's present I know that the device is a Motorola.
    but, now, I have some devices (V8) that didn't support this class, so how can I do otherwise ?
    I saw that there's an API named get URL from flex, but i don't now more about !
    some one can help me ?
    Regards, Idir

    check this out
    // detecting NOKIA or SonyEricsson 
                      try { 
                               final String currentPlatform = System.getProperty("microedition.platform"); 
                               if (currentPlatform.indexOf("Nokia") != -1) { 
                                   return "nokia"; 
                               } else if (currentPlatform.indexOf("SonyEricsson") != -1) { 
                                   return "SE"; 
                      } catch (Throwable ex) { 
                   // detecting SAMSUNG 
                      try { 
                               Class.forName("com.samsung.util.Vibration"); 
                               return "samsung";
                      } catch (Throwable ex) { 
                   // detecting MOTOROLA 
                      try { 
                               Class.forName("com.motorola.multimedia.Vibrator"); 
                               return "motorola";
                      } catch (Throwable ex) { 
                               try { 
                                   Class.forName("com.motorola.graphics.j3d.Effect3D"); 
                                   return "motorola";
                               } catch (Throwable ex2) { 
                                   try { 
                                            Class.forName("com.motorola.multimedia.Lighting"); 
                                            return "motorola";
                                   } catch (Throwable ex3) { 
                                            try { 
                                                Class.forName("com.motorola.multimedia.FunLight"); 
                                                return "motorola";
                                            } catch (Throwable ex4) { 
                   // detecting SIEMENS
                      try { 
                               Class.forName("com.siemens.mp.io.File"); 
                               return "siemens"; 
                      } catch (Throwable ex) { 
                   // detecting LG 
                      try { 
                               Class.forName("mmpp.media.MediaPlayer"); 
                               return "LG";
                      } catch (Throwable ex) { 
                               try { 
                                   Class.forName("mmpp.phone.Phone"); 
                                   return "LG";
                               } catch (Throwable ex1) { 
                                   try { 
                                            Class.forName("mmpp.lang.MathFP"); 
                                            return "LG";
                                   } catch (Throwable ex2) { 
                                            try { 
                                                Class.forName("mmpp.media.BackLight"); 
                                                return "LG";
                                            } catch (Throwable ex3) { 
                      }  pravin

  • How can I ensure that there is no personal data on my HP Officejet Pro 8500 when I donate it?

    I have a HP OfficeJet Pro 8500 series printer (A909) that I want to donate to a local charity.  However, I am concerned that there could be personal information stored on it (taxes, financial records, etc).  How can I make sure that there is no personal info left before I donate it?

    Hope you are doing well and welcome to the hp forums,
    If you still need assistance I will do my best to help you
    Go to this article and follow this instrucition it should erase all user data from it.
    http://h10025.www1.hp.com/ewfrf/wc/document?docname=c01631212&cc=us&dlc=en&lc=en&product=3752456
    If you are not experiencing this issue any longer please let me know it will deeply appreciated.
    Hope this helps!
    RobertoR
    remember↓↓↓ 
    You can say THANKS by clicking the KUDOS STAR. If my suggestion resolves your issue Mark as a "SOLUTION" this way others can benefit Thanks in Advance!

  • How can i detected that the channel is closed with nio async?

    using nio, I can wait accept, read data, write data asynchronously.
    now i make a server program, and want to dected if a socket is closed by client, how can i do this?
    thanks.

    TO: ejp
    In TCP the only way you can detect a dead connection is to attempt to write to it.
    Eventually this will fail probably with a SocketException 'connection reset'.When should this happen? I don't seem to get any expection. The socket is registered for read only but it never gets read for reading again. The appropriate selection key indicates it is writable, but I don't have it registered for write operation.
    Isn't there any other way to get around those dead sockets without trying to write at them? This would be quite an overhead, since server has to send some check_alive message periodically...

  • I recently reinstalled Acrobat 8.1.  When I try to check for updates, it says that there's no internet connection.  I have checked settings and firewall.  No issues.  What's wrong?

    I recently reinstalled Acrobat 8.1 after a crash.  I wanted to check for updates but encountered the message that no internet connection was found, to check the internet settings or the firewall.  There are no issues with either.  Obviously, I have an internet connection.  How do I resolve this issue?

    Hello Coldwater Card,
    Please try the following steps and let us know if this fix your issue :
    Operating system hosts files map host names to IP addresses. An incorrectly configured hosts file can affect your computer's ability to connect to Adobe's activation servers.
    Follow these steps to see if there is a problem with your hosts file and to reset it if necessary.
    Click this link.
    If you see two Adobe logos, then you have access to the activation servers. Try activating or starting your software.
    Still have problems? Go to the next step.
    Start an internet browser, such as Firefox or Internet Explorer, and go to:
    CS5.5: https://activate.adobe.com/test
    CS6 and later: https://lm.licenses.adobe.com/gdf/status.jsp
    If you see a test successful message (see screenshots below), then you have access to the activation servers. Try activating or starting your software. 
    CS5.5: Test successful
    CS6 and later: Test successful
    Still have problems? Proceed to Step 3. Reset the hosts file.
    Reset the hosts file: 
    NOTE: You may have to disable you security software to modify your hosts file.
    Windows
    Choose Start > Run, type %systemroot% \system32\drivers\etc, and then press Enter.
    Right-click the hosts file and select Open. Select Notepad for the application to open the hosts file.
    Back up the hosts file: Choose File > Save As, save the file ashosts.backup, and then click OK.
    Search the hosts file for entries that reference activate.adobe.com (for example, 127.0.0.1 activate.adobe.com) and delete these entries.
    Save and close the file.
    Mac OS
    Log in as an administrator to edit the hosts file in Mac OS.
    In a Finder window, choose Go > Go To Folder.
    Type /etc.
    Select the hosts file and open it.
    Back up the hosts file: Choose File > Save As, save the file ashosts.backup, and then click OK.
    Search the hosts file for entries that reference activate.adobe.com (for example, 127.0.0.1 activate.adobe.com) and delete these entries.
    Save and close the file.

  • How can i call javascript function with out internet connection?

    I have trying to call javascript function through ExternalInterface. But flash player recomonding to have internet connectivity. i have allredy used allowscript="always" .

    first, allow the folder that contains your flash files to connect to the internet by adjusting your security settings:
    http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04a.ht ml
    then try the following in a swf and open the published html in your browser to test:
    import flash.external.ExternalInterface
    ExternalInterface.call("function(){alert('test');}")

  • How can i set my ipod up without internet connection? Every-time I put my network in it say "Could not find network".

    My I-pod wont connect with the network, so I reset my I-pod to see if that was the problem
    and now I cant set my I-pod up because my I-pod cant find the network. I cant download I-tunes
    on my laptop because I have to have a password that I don't know.

    Try either:
    - On a computer that has iTunes and an internet connection
    - Go to a different location and try connecting to another wifi network

  • How can I detect that a step was forced to fail or forced to pass?

    When I set one step to ForceFail, and another step to ForcePass, and I run the test sequence, the ResultStatus is just "Failed" or "Passed" without providing any feedback that it was not a true test.  Is there a way to detect / document this?
    Solved!
    Go to Solution.

    I'll do you one better, here's a working example. It uses the SequenceFilePostResultListEntry callback, but you could also implement it in process model using ProcessModelPostResultListEntry. You may have to modify your stylesheet to get results to populate correctly, particularly with XML or ATML reporting.
    It's pretty simple: if the reporting step uses either Force Pass or Force Fail, the callback updates both the UI's ResultStatus and the Result.Status going into the report. If you only want one or the other, remove or comment out the part you don't want.
    Attachments:
    ForcedPostStepExample.seq ‏6 KB

  • How Can I limit the bandwith of my internet connection on linux?

    Hello, I have 2 Pc's, one for my brother, and the other for me. And well, always we have problems about downloads and lags when we are playing.
    For example, when I download packages from pacman, it is done at maximum speed "eating" all connection, and my brother has lag.
    Is there anyway to limit the bandwith that use my programs to half, for example? If maximum download speed is 100KB/s, pacman only can download 50 KB/s maximum.
    Greetings

    Depending on your router you may be able to set Ingress Rate Limit under QoS. Also have a look into trickle: http://aur.archlinux.org/packages.php?d … s=0&SeB=nd
    http://monkey.org/~marius/pages/?page=trickle
    Last edited by somairotevoli (2007-07-21 01:42:55)

  • My computer is running very slow, how can I tell if it is a internet connection problem or my computer?

    I have a mac 10.5.8 and it has been very slow lately. I often get the rainbow wheel when using it and recently I have had to restart the computer alot because it seems to freeze. The only other open program besides Safari is the finder which i cant seems to ever shut off. I'm not sure if this is an interent connection problem or if my mac needs servicing.

    Please begin using 25 Ways to Speed Up Your Mac  you will almost certainly find the cause there. The first place I'd look though is how much RAM your system has, if you never upgraded it that could be the problem. Macs ship with a minimum amount of RAM so it's possible a simple RAM upgrade would help. Use the article though and methodically go through the suggestions.
    You also may benefit by reading XLab's Spinning Beach Ball of Death article too.

  • How can I detect in Business HTML that the app was called from portal?

    How can I detect in Business HTML that the app was called from portal?
    I need to distinguish whether the application was called from portal (URL iView) or by using an URL outside of portal.
    So what I'm looking for is a variable or function that can be used like this:
    `if (~within_portal==1)`
      do this if called from portal
    `else;`
      do that if not called from portal
    `end;`
    For example, can I check in the program that there is a SSO2 cookie from the portal?
    I'm using Integrated ITS in Basis 700.

    Here is the trick:
      if (sapwp_active=="1")
        in portal
      else
        without portal
      end;

  • I am receiving the data through the rs232 in labview and i have to store the data in to the word file only if there is a change in the data and we have to scan the data continuasly how can i do that.

    i am receiving the data through the rs232 in labview and i have to store the data in to the word or text file only if there is a change in the data. I have to scan the data continuasly. how can i do that. I was able to store the data into the text or word file but could not be able to do it.  I am gettting the data from rs232 interms of 0 or 1.  and i have to print it only if thereis a change in data from 0 to 1. if i use if-loop , each as much time there is 0 or 1 is there that much time the data gets printed. i dont know how to do this program please help me if anybody knows the answer

    I have attatched the vi.  Here in this it receives the data from rs232 as string and converted into binery. and indicated in led also normally if the data 1 comes then the led's will be off.  suppose if 0 comes the corresponding data status is wrtten into the text file.  But here the problem is the same data will be printed many number of times.  so i have to make it like if there is a transition from 1 to o then only print it once.  how to do it.  I am doing this from few weeks please reply if you know the answer immediatly
    thanking you 
    Attachments:
    MOTORTESTJIG.vi ‏729 KB

Maybe you are looking for

  • Playing MP4 Files

    I just bought a new video camera which records in HD and creates an Mp4 movie file. How do I play this file on my Mac? I am not an overly technical person, but have never had an issue where my Mac was unable to read a video file. Help.

  • Do I need OS 9 (not Classic)?

    Am running 10.4.5 on a Mini. Bought a MiniStack in which I put a HD from my Beige G3 with 10.2.8 and 9.2.2 on it. I could run Jaguar and OS 9 applications without any noticable problems. But, that older HD is too noisy (wasn't noticable in the G3) an

  • Integration wth outide Job Scheduler.

    We are looking at integrating the Vinizant Global ECS Job scheduler with SAP.   We need to know how to start and monitor sap jobs and chains from unix level. Any suggestions would be appreciated.

  • How can i align submenu in Spry horizontal menu ?

    Hello everybody, new to spry menus but got one working in chrome, safari and ff. IE however is giving me problems and i can't figure it out alone anymore. The submenus align fine in all browsers except IE. There the submenus don't drop down but displ

  • I want all system status for all process orders in COR3

    Hi All, I have small requirement below: In COR3 tcode after we enter Process order as input, in that screen we can see in 3rd row, System Status and User Status, Where all these system status and User Status are stored, How we will get these msgs? Pl