def bind_port(sock, host=HOST):
if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:<EOL><INDENT>if hasattr(socket, '<STR_LIT>'):<EOL><INDENT>if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == <NUM_LIT:1>:<EOL><INDENT>raise TestFailed("<STR_LIT>""<STR_LIT>")<EOL><DEDENT><DEDENT>if hasattr(socket, '<STR_LIT>'):<EOL><INDENT>if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == <NUM_LIT:1>:<EOL><INDENT>raise TestFailed("<STR_LIT>""<STR_LIT>")<EOL><DEDENT><DEDENT>if hasattr(socket, '<STR_LIT>'):<EOL><INDENT>sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, <NUM_LIT:1>)<EOL><DEDENT><DEDENT>sock.bind((host, <NUM_LIT:0>))<EOL>port = sock.getsockname()[<NUM_LIT:1>]<EOL>return port<EOL>
Bind the socket to a free port and return the port number.  Relies on
    ephemeral ports in order to ensure we are using an unbound port.  This is
    important as many tests may be running simultaneously, especially in a
    buildbot environment.  This method raises an exception if the sock.family
    is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
    or SO_REUSEPORT set on it.  Tests should *never* set these socket options
    for TCP/IP sockets.  The only case for setting these options is testing
    multicasting via multiple UDP sockets.

    Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
    on Windows), it will be set on the socket.  This will prevent anyone else
    from bind()'ing to our host/port for the duration of the test.