Bug in socket.connect_ex() implementation or docs ?!

Guido van Rossum guido at eric.cnri.reston.va.us
Thu May 6 16:53:17 EDT 1999


"Barry A. Warsaw" <bwarsaw at cnri.reston.va.us> writes:

> >>>>> "M" == M  <mal at lemburg.com> writes:
> 
>     MAL> I just noticed that the .connect_ex() does raise
>     MAL> socket.errors, even though the docs say, it does not. The
>     MAL> exception I get is:
> 	
>     MAL> 	socket.error: host not found
> 
>     MAL> I think either the docs or the implementation should be
>     MAL> changed...  guess which one is simpler ;-)
> 
> Dang, you're right.  This is happening because three calls up --
> gethostbyname() inside getsockaddrarg() inside getsockaddrarg() --
> is failing and setting the exception.
> 
> It's not clear to me what the code fix would be.  Should connect_ex()
> clear the exception and return h_error when it finds that
> getsockaddrarg() failes?  What if there is no h_error?  And how is
> this fact best propagated back down to PySocketSock_connect_ex()?
> 
> Note that there's an easy workaround: call gethostbyname first
> yourself and catch any exceptions there.  If valid, pass the resulting
> IP address to connect_ex(), e.g.:
> 
> try:
>     ip = socket.gethostbyname('somemachine')
>     conn = s.connect_ex(ip, PORT)
> except socket.error:
>     pass
> 
> Does this defeat too much of the purpose of connect_ex()?
> 
> -Barry

I see no reason to fix the code.  connect_ex() exists for the very
specific purpose to allow non-blocking connects without the overhead
of setting up a try/except and catching an exception (which amounts to 
"not yet").  I think it's actually a feature that if there's something 
else wrong (as in this case, where the C code never reaches the actual 
connect() system call) an exception is raised.

The docs should be fixed.

--Guido van Rossum (home page: http://www.python.org/~guido/)




More information about the Python-list mailing list