def bind_port(sock, host='<STR_LIT>', preferred_port=<NUM_LIT>):
import socket, errno<EOL>for port in [preferred_port, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT:0>]:<EOL><INDENT>try:<EOL><INDENT>sock.bind((host, port))<EOL>if port == <NUM_LIT:0>:<EOL><INDENT>port = sock.getsockname()[<NUM_LIT:1>]<EOL><DEDENT>return port<EOL><DEDENT>except socket.error as xxx_todo_changeme:<EOL><INDENT>(err, msg) = xxx_todo_changeme.args<EOL>if err != errno.EADDRINUSE:<EOL><INDENT>raise<EOL><DEDENT>print('<STR_LIT>' % port, file=sys.__stderr__)<EOL><DEDENT><DEDENT>raise TestFailed('<STR_LIT>')<EOL>
Try to bind the sock to a port.  If we are running multiple
    tests and we don't try multiple ports, the test can fails.  This
    makes the test more robust.