Try: Except: evaluates to True every time

Steve D'Aprano steve+python at pearwood.info
Sat Nov 4 12:00:46 EDT 2017


On Sun, 5 Nov 2017 02:31 am, brandon wallace wrote:

> 
> I have this code that tests a server to see if it is listening on port 123
> runs and evaluates to True every time. Even if the server does not exist but
> it is not supposed to do that. I am getting no error message at all. What is
> going on with this code?

You're returning a string in both cases. Both strings evaluate as true when
treated as bools.

Success:

> return "Port 53 is reachable on: %s" % host

Failure:

> except socket.error as e:
>     return "Error on connect: %s" % e
> 
> check_udp(hostname, port)


That's the first bug. The second bug is that I don't think the code does what
you think it does. You seem to be calling it with a single hostname,
presumably a string. But then you split the hostname into individual letters,
and try to connect to each of them. The *first* attempt either succeeds or
fails, and then returns.

So if you call check_udp("mailserver", 143), your function calls

    for host in "mailserver":
        try:
            s.connect((host, port_num))


which attempts to connect to ("m", 143). That will either succeed (probably
not), or fail (probably this), and then the function returns a string, which
you apparently never look at.

I suggest you re-write your check_udp function to something more like this:


def check_udp(host, port_num):
    '''Test the UDP port on a remove server.'''
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect((host, port_num))
        return True
    except socket.error as e:
        return False


But even this is suspicious, since it is vulnerable to a "Time Of Check To
Time Of Use" bug. Just because you can connect to the host *now*, when you
call check_udp, doesn't mean it will still respond two seconds later (or even
two milliseconds later) when you attempt to connect again.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list