1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2004
    Rep Power

    Question How to know that PC is connected to internet through code?

    Well as mentioned in subject I just want to know that when i starts my Python application, I have to find that whether Internet is connected or not?

    If internet is connected then my application should raise message?

    How this can be done?

    Thanks in Advance
  2. #2
  3. Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Dec 2004
    Meriden, Connecticut
    Rep Power
    Taken from ASPN.
    PyHeartbeat detects inactive computers by sending and receveing "heartbeats" as UDP packets on the network, and keeping track of how much time passed since each known computer sent its last heartbeat. The concurrency in the server is implemented using threads first, and then again using the Twisted Matrix framework.
    Source: Text Source
    # Filename: HeartbeatClient.py
    """Heartbeat client, sends out an UDP packet periodically"""
    import socket, time
    SERVER_IP = ''; SERVER_PORT = 43278; BEAT_PERIOD = 5
    print ('Sending heartbeat to IP %s , port %d\n'
        'press Ctrl-C to stop\n') % (SERVER_IP, SERVER_PORT)
    while True:
        hbSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        hbSocket.sendto('PyHB', (SERVER_IP, SERVER_PORT))
        if __debug__: print 'Time: %s' % time.ctime()
    --- 8< --- snip --- 8< --- snip --- 8< --- snip --- 8< ---
    # Filename: ThreadedBeatServer.py
    """Threaded heartbeat server"""
    import socket, threading, time
    class Heartbeats(dict):
        """Manage shared heartbeats dictionary with thread locking"""
        def __init__(self):
            super(Heartbeats, self).__init__()
            self._lock = threading.Lock()
        def __setitem__(self, key, value):
            """Create or update the dictionary entry for a client"""
            super(Heartbeats, self).__setitem__(key, value)
        def getSilent(self):
            """Return a list of clients with heartbeat older than CHECK_TIMEOUT"""
            limit = time.time() - CHECK_TIMEOUT
            silent = [ip for (ip, ipTime) in self.items() if ipTime < limit]
            return silent
    class Receiver(threading.Thread):
        """Receive UDP packets and log them in the heartbeats dictionary"""
        def __init__(self, goOnEvent, heartbeats):
            super(Receiver, self).__init__()
            self.goOnEvent = goOnEvent
            self.heartbeats = heartbeats
            self.recSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.recSocket.bind((socket.gethostbyname('localhost'), UDP_PORT))
        def run(self):
            while self.goOnEvent.isSet():
                    data, addr = self.recSocket.recvfrom(5)
                    if data == 'PyHB':
                        self.heartbeats[addr[0]] = time.time()
                except socket.timeout:
    def main():
        receiverEvent = threading.Event()
        heartbeats = Heartbeats()
        receiver = Receiver(goOnEvent = receiverEvent, heartbeats = heartbeats)
        print ('Threaded heartbeat server listening on port %d\n'
            'press Ctrl-C to stop\n') % UDP_PORT
            while True:
                silent = heartbeats.getSilent()
                print 'Silent clients: %s' % silent
        except KeyboardInterrupt:
            print 'Exiting, please wait...'
            print 'Finished.'
    if __name__ == '__main__':
    --- 8< --- snip --- 8< --- snip --- 8< --- snip --- 8< ---
    # Filename: TwistedBeatServer.py
    """Asynchronous events-based heartbeat server"""
    import time
    from twisted.application import internet, service
    from twisted.internet import protocol
    from twisted.python import log
    class Receiver(protocol.DatagramProtocol):
        """Receive UDP packets and log them in the clients dictionary"""
        def datagramReceived(self, data, (ip, port)):
            if data == 'PyHB':
    class DetectorService(internet.TimerService):
        """Detect clients not sending heartbeats for too long"""
        def __init__(self):
            internet.TimerService.__init__(self, CHECK_PERIOD, self.detect)
            self.beats = {}
        def update(self, ip):
            self.beats[ip] = time.time()
        def detect(self):
            """Log a list of clients with heartbeat older than CHECK_TIMEOUT"""
            limit = time.time() - CHECK_TIMEOUT
            silent = [ip for (ip, ipTime) in self.beats.items() if ipTime < limit]
            log.msg('Silent clients: %s' % silent)
    application = service.Application('Heartbeat')
    # define and link the silent clients' detector service
    detectorSvc = DetectorService()
    # create an instance of the Receiver protocol, and give it the callback
    receiver = Receiver()
    receiver.callback = detectorSvc.update
    # define and link the UDP server service, passing the receiver in
    udpServer = internet.UDPServer(UDP_PORT, receiver)
    # each service is started automatically by Twisted at launch time
    log.msg('Asynchronous heartbeat server listening on port %d\n'
        'press Ctrl-C to stop\n' % UDP_PORT)
    How it works
    When we have a number of computers, we are often interested in monitoring their working state. It is possible to detect when a computer stops working by using a pair of programs, one client and one server.
    The client program, running on any number of computers, periodically sends an UDP packet to the server program, listening on one computer. The server program dinamically builds a dictionary that stores the IP addresses of the client computers, and the time stamp of the last packet received from each one. At the same time it periodically checks the dictionary, checking whether any of the time stamps is older than a defined timeout.
    In this kind of application there is no need to use reliable TCP connections, since the loss of a packet now and then does not produce false alarms, given that the server checking timeout is kept suitably larger than the client sending period. On the other hand, if we have hundreds of computers to monitor, it is preferable to keep the bandwith used and the load on the server at a minimum. We obtain this by periodically sending a small UDP packet, instead of setting up a
    comparably expensive TCP connection each time.
    The packets are sent from each client with a period of five seconds, while the server checks the dictionary with a period of twenty seconds, and its timeout is set to fifteen seconds. These parameters, along with the server IP address and port used, may be configured to one's needs.
    Threaded server
    In the threaded server, one thread listens to the UDP packets coming from the clients, while the main thread periodically checks the recorded heartbeats. The shared data structure, a dictionary, must be locked and released at each access, both while writing and reading, to avoid data corruption on concurrent access. Such data corruption often manifests itself as intermittent, time-dependent bugs that are difficult to reproduce, investigate and correct.
    Twisted server
    The Twisted server employs an asynchronous, event driven model, being based on the Twisted Matrix framework ( http://www.twistedmatrix.com/ ). The framework is built around a central "reactor" that dispatches events from a queue in a single thread, and monitors network and host resources. The user program is composed of short code fragments invoked by the reactor when dispatching the matching events. Such a working model guarantees that only one user code fragment is being executed at any given time, eliminating at the root all problems of concurrent access to shared data structures.
    The server program is composed of an Application and two Services, the UDPServer and the DetectorService. It is invoked by means of the "twistd" command, with the following options:
    $ twistd -ony TwistedBeatServer.py
    See the Twisted Matrix documentation for further information.
    This program has been tested on Python 2.3.4 and Twisted 1.3.0 . It will work on Python 2.2 by substituting the three occurrences of the "super" keyword in the ThreadedBeatServer.py file with the corresponding old form.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2004
    Rep Power
    if you are just trying to see if there internet connection is up, you could try using urllib2 and urlopening the address say like google and if it works then great you know it is up, if not, then you know something is wrong.

    if you need code ask and i will post it.
  6. #4
  7. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Hull, UK
    Rep Power
    Another way to do this would be to use the ping command from Python, which should be available on most if not all Operating Systems; though the implementation may vary.

    You can do this using the subprocess module under Python2.4 or using the os.system(), os.popen() or the popen2 functions etc. In this example I've used subprocess.call().

    #!/usr/bin/env python
    from subprocess import call, PIPE
    returnCode = call(('ping', '-c', '1', ''), stdout = PIPE,
                                                            stderr = PIPE)
    if returnCode == 0:
        print 'Connected!'
        print 'Not Connected!'
    Note: I've only been able to test this code on my Mac but it should work fine anywhere. If not let me know .

    Hope this helps,


    Comments on this post

    • CyBerHigh agrees : Yes, this will work on windows and linux as well.
    programming language development: www.netytan.com Hula

  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2004
    Rep Power
    Thanks for your feedback. Well I will try this out and let you know


IMN logo majestic logo threadwatch logo seochat tools logo