ftplib.FTP timeout has inconsistent behaviour

后端 未结 2 790
清酒与你
清酒与你 2021-01-20 02:20

I am trying to use ftplib.FTP() with timeout option as some timeout value for a particular hostname. But i am experiencing weird behaviour. To test it i have wr

2条回答
  •  离开以前
    2021-01-20 02:54

    ftplib.FTP invokes socket.create_connection(). According to the docs https://docs.python.org/2/library/socket.html#socket.create_connection

    if host is a non-numeric hostname, it will try to resolve it for both AF_INET and AF_INET6, and then try to connect to all possible addresses in turn until a connection succeeds.

    A quick check of google.com will show about a dozen (or more) depending on your region of the country. Your 2 second timeout is applied to each of the hosts.

    If you want to limit total time to 2 seconds, do the lookup first and pass the numeric address to your ftplib.FTP call:

    import socket, ftplib
    host = socket.gethostbyname('google.com')
    ftp = ftplib.FTP(host, timeout=2)
    

提交回复
热议问题