def bind(socket, connection, port):
    """Binds a socket to a port, or a random port if needed. Returns the port."""
    if port <= 0:
        return socket.bind_to_random_port(connection)
    else:
        socket.bind(f"{connection}:{port}")
    return port