Python 2.7 behavior socket.timeout

Below are two simple python functions. First, it tries to connect to test.comthe 666 domain (the host name is valid, but the port is not). The second tries to connect to imap.mail.outlook.comon port 993 (the host name is valid, but does not look for public use / access).

def fn_outlook(timeout):
    try:
        socket.create_connection(("imap.mail.outlook.com", 993), timeout=timeout)
    except socket.timeout:
        pass


def fn_test(timeout):
    try:
        socket.create_connection(("test.com", 666), timeout=timeout)
    except socket.timeout:
        pass

And here is the runtime for this function with different timeouts:

In [14]: %time fn_test(1)
CPU times: user 644 µs, sys: 1.07 ms, total: 1.71 ms
Wall time: 1 s

In [15]: %time fn_test(2)
CPU times: user 589 µs, sys: 1.15 ms, total: 1.74 ms
Wall time: 2 s

In [16]: %time fn_outlook(2)
CPU times: user 838 µs, sys: 2.24 ms, total: 3.08 ms
Wall time: 7.15 s

In [17]: %time fn_outlook(4)
CPU times: user 705 µs, sys: 1.18 ms, total: 1.88 ms
Wall time: 12 s

In [18]: %time fn_test(4)
CPU times: user 483 µs, sys: 795 µs, total: 1.28 ms
Wall time: 4.42 s

In case, the test.comconnection will be disconnected after the same time as in the argument timeout. But for imap.mail.outlook.comeverything, it becomes interesting - socket connections ignore the timeout argument. To be precise, do not ignore, but rather always connect timeouts after some longer period of time.

, imap.mail.outlook.com, .

+4
1

-, :

def fn_connect(host, port, timeout):
    try:
        s = socket.create_connection((host, port), timeout=timeout)
    except socket.timeout:
        return None
    else:
        return s

:

IMAP_HOST = "imap.mail.outlook.com"
IMAP_PORT = 993
TEST_HOST = "test.com"
TEST_PORT = 666
s1 = fn_connect(IMAP_HOST, IMAP_PORT, 2)
s2 = fn_connect(TEST_HOST, TEST_PORT, 1)
#and so on....

, ( not None).

, ; create_connection getaddrinfo, (, -, ). , 2- :

  • TEST_HOST, TEST_PORT

    socket.getaddrinfo("test.com", 666)
    [(2, 0, 0, '', ('69.172.200.235', 666))]
    
  • IMAP_HOST, IMAP_PORT

    socket.getaddrinfo("imap.mail.outlook.com", 993)
    [(2, 0, 0, '', ('207.46.163.247', 993)),
     (2, 0, 0, '', ('207.46.163.138', 993)),
     (2, 0, 0, '', ('207.46.163.215', 993))]
    

, IMAP_HOST IMAP_PORT 3 ( TEST_HOST, TEST_PORT ). , , , ~ 3 , .

+4

Source: https://habr.com/ru/post/1614304/