Handling a timeout error in python sockets

前端 未结 4 2105
醉话见心
醉话见心 2020-12-14 15:38

I am trying to figure out how to use the try and except to handle a socket timeout.

from socket import *

def main():
    client_socket = socket(AF_INET,SOC         


        
4条回答
  •  误落风尘
    2020-12-14 16:24

    Here is a solution I use in one of my project.

    network_utils.telnet

    import socket
    from timeit import default_timer as timer
    
    def telnet(hostname, port=23, timeout=1):
        start = timer()
        connection = socket.socket()
        connection.settimeout(timeout)
        try:
            connection.connect((hostname, port))
            end = timer()
            delta = end - start
        except (socket.timeout, socket.gaierror) as error:
            logger.debug('telnet error: ', error)
            delta = None
        finally:
            connection.close()
    
        return {
            hostname: delta
        }
    

    Tests

    def test_telnet_is_null_when_host_unreachable(self):
        hostname = 'unreachable'
    
        response = network_utils.telnet(hostname)
    
        self.assertDictEqual(response, {'unreachable': None})
    
    def test_telnet_give_time_when_reachable(self):
        hostname = '127.0.0.1'
    
        response = network_utils.telnet(hostname, port=22)
    
        self.assertGreater(response[hostname], 0)
    

提交回复
热议问题