import socket


def Bind(port, socket_type, socket_proto):
  """Try to bind to a socket of the specified type, protocol, and port.

  This is primarily a helper function for PickUnusedPort, used to see
  if a particular port number is available.

  Args:
    port: The port number to bind to, or 0 to have the OS pick a free port.
    socket_type: The type of the socket (ex: socket.SOCK_STREAM).
    socket_proto: The protocol of the socket (ex: socket.IPPROTO_TCP).

  Returns:
    The port number on success or None on failure.
  """
  s = socket.socket(socket.AF_INET, socket_type, socket_proto)
  try:
    try:
      s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
      s.bind(('', port))
      return s.getsockname()[1]
    except socket.error:
      return None
  finally:
    s.close()