Try: Except: evaluates to True every time

Chris Angelico rosuav at gmail.com
Sat Nov 4 13:10:58 EDT 2017


On Sun, Nov 5, 2017 at 2:31 AM, brandon wallace <nodnarb at gmx.us> 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?
>
>
>
> #!/usr/bin/env python
>
> import socket
>
> hostname = ["192.168.1.22", "192.168.1.23", "200.168.1.24", "19.0.0.0"]
> port = 123
>
> def check_udp(hosts, port_num):
>     '''Test the UDP port on a remove server.'''
>     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
>     for host in hosts:
>         try:
>             s.connect((host, port_num))
>             return "Port 53 is reachable on: %s" % host
>         except socket.error as e:
>             return "Error on connect: %s" % e
>
> check_udp(hostname, port)

Do you understand what it actually means to connect a UDP socket? If
not, I suggest reading up on the nature of UDP. You can't probe a
remote server this way; it simply doesn't work like that.

ChrisA



More information about the Python-list mailing list