getting socket.bind() exception, but no actual error

Michael Fuhr mfuhr at fuhr.org
Tue Nov 2 23:05:51 EST 2004


Steve Holden <steve at holdenweb.com> writes:

> Michael Fuhr wrote:
>
> > clarence at silcom.com (Clarence Gardner) writes:
> > 
> >>And the whole point of the test in the exception handling suite (checking
> >>for "in use") is to repeat the bind until that's not the case. This is, of
> >>course, in a program in development which sometimes is not able to be 
> >>restarted right away after a problem.
> > 
> > Why not?  Because you get "Address already in use" exceptions due
> > to old connections still being in the TIME_WAIT state?  If so, are
> > you aware that server processes should usually set the SO_REUSEADDR
> > socket option before calling bind()?  Or is there some other reason
> > that bind() fails?
>
> There is some other reason: the exception argument is (errno 22, Invalid 
> argument), which is clearly not "Address in use".

The retry loop likely isn't solving this problem but is rather
causing it.  The code originally posted was:

    sockobj=socket(AF_INET,SOCK_STREAM)
    while True:
        try:
            sockobj.bind(('',4321))
        except socketerror,e:
            print e
            if str(e).find('in use') == -1:
                break
            print '.'
            time.sleep(1)
    sockobj.listen(5)

Think about what happens if bind() succeeds: the code never breaks
out of the while loop, so it attempts to call bind() again.  On
most systems that will cause the second call to bind() to fail with
EINVAL, or "Invalid argument".  You could break out of the loop
when bind() succeeds, but the loop should be unnecessary if you set
the SO_REUSEADDR socket option before calling bind(), like this:

sockobj.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)

Any decent network programming book (e.g., _UNIX Network Programming_,
Vol 1, by W. Richard Stevens) will explain that servers should set
SO_REUSEADDR before calling bind().

-- 
Michael Fuhr
http://www.fuhr.org/~mfuhr/



More information about the Python-list mailing list