Find a port number for this instance to listen on. We just check that nothing is already listening on it.
 The process is expected to take it straight away if it wants it.
968444
def allocate_port(max_attempts = 10)
      attempts = 0
      until @port
        attempts += 1
        possible_port = rand(10000) + 20000
        if self.port_available?(possible_port)
          Procodile.log(@process.log_color, description, "Allocated port as #{possible_port}")
          return @port = possible_port
        elsif attempts >= max_attempts
          raise Procodile::Error, "Couldn't allocate port for #{instance.name}"
        end
      end
    end
37005
function (ui, done) {
        var port = ui.options.get("port");
        var listenHost = ui.options.get("listen", "localhost");
        ui.bs.utils.portscanner.findAPortNotInUse(port, port + 100, {
            host: listenHost,
            timeout: 1000
        }, function (err, port) {
            if (err) {
                return done(err);
            }
            done(null, {
                options: {
                    port: port
                }
            });
        });
    }
411209
def start_if_necessary(self):
        
        self.lock.acquire()
        try:
            if not self.listening:
                self.init()

                self.listening = True
                self.listening_thread = Thread(target=self.listen)
                self.listening_thread.daemon = True
                self.listening_thread.start()

                self.processing_thread = Thread(target=self.process)
                self.processing_thread.daemon = True
                self.processing_thread.start()
        finally:
            self.lock.release()
280806
def detect_port(port):
    ''''''
    socket_test = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    try:
        socket_test.connect(('127.0.0.1', int(port)))
        socket_test.close()
        return True
    except:
        return False
1215858
def is_http_running_on(port):
  
  try:
    conn = httplib.HTTPConnection('127.0.0.1:' + str(port))
    conn.connect()
    conn.close()
    return True
  except Exception:
    return False
873692
function nextPort(port) {
  if (!port) {
    return 8000;
  }

  //
  // Find the next port that we are not supposed to ignore or cause errors on
  //
  var unavailable = carapace.ports.ignore.concat(carapace.ports.throw);
  do {
    port = port + 1;
  } while (unavailable.indexOf(port) !== -1);

  return port;
}
1066831
def check_port(helper, port):
    
    try:
        int(port)
    except ValueError:
        helper.exit(summary="Port (-p) must be a integer value.", exit_code=unknown, perfdata='')
872947
def available_tcp_port(reactor):
    

    endpoint = serverFromString(reactor, 'tcp:0:interface=127.0.0.1')
    port = yield endpoint.listen(NoOpProtocolFactory())
    address = port.getHost()
    yield port.stopListening()
    defer.returnValue(address.port)
1198601
def start_tcp_server(self, port):
        

        self.__tcp_server.port = port
        if not self.__tcp_server.online:
            if self.__tcp_server.start():
                self.__engine.notifications_manager.notify(
                    "{0} | TCP Server has started with '{1}' address on '{2}' port!".format(
                        self.__class__.__name__,
                        self.__address,
                        self.__port))
                return True
        else:
            self.__engine.notifications_manager.warnify(
                "{0} | TCP Server is already online!".format(self.__class__.__name__))
            return False
698225
def accepts_port(self, port):
        

        if self.rejected_ports is None and self.accepted_ports is None:
            raise RuntimeError("policy hasn't been set yet")

        if self.rejected_ports:
            for x in self.rejected_ports:
                if port == x:
                    return False
            return True

        for x in self.accepted_ports:
            if port == x:
                return True
        return False
391848
def port_available?(port)
      case @process.network_protocol
      when 'tcp'
        server = TCPServer.new('127.0.0.1', port)
        server.close
        true
      when 'udp'
        server = UDPSocket.new
        server.bind('127.0.0.1', port)
        server.close
        true
      else
        raise Procodile::Error, "Invalid network_protocol '#{@process.network_protocol}'"
      end
    rescue Errno::EADDRINUSE => e
      false
    end
973490
def valid_port(port)
      port_number = port.to_s.to_i(10) if /\A[0-9]+\z/ =~ port.to_s
      port_number if (1...2**16).cover? port_number
    end
362266
def has_port_by_name(self, port_name):
        ''''''
        with self._mutex:
            if self.get_port_by_name(port_name):
                return True
            return False
368871
def get_port_monitor(self):
        
        uri = "{}{}".format(self.data["uri"], self.PORT_MONITOR_PATH)
        return self._helper.do_get(uri)
311913
def commission
      response = nil
      begin
        unlock_network
        Timeout.timeout(30) do
          @logger.info("Listening for devices ...")
          loop do
            buffer = @serial.receive(4)
            buffer += @serial.receive(buffer.bytes.to_a[3]+1)
            if buffer.bytes.to_a[1] == 0xa0
              response = BroadcastResponse.read(buffer)
              @logger.info("Found device 0x%x on network 0x%x" % [response.device_id, response.network_id])
              break
            end
          end
        end
      rescue Timeout::Error
      ensure
        lock_network
      end

      update_time(response.network_id) if response
    end
1246732
def listen(self):
        

        # Make sure we're in server mode
        if self.mode and self.mode != 'server':
            raise ValueError("%s is not in server mode" %
                             self.__class__.__name__)
        self.mode = 'server'

        # Obtain a listening socket
        serv = _create_server(self.host, self.port)

        # If we have too many errors, we want to bail out
        err_thresh = 0
        while True:
            # Accept a connection
            try:
                sock, addr = serv.accept()
            except Exception as exc:
                err_thresh += 1
                if err_thresh >= self.max_err_thresh:
                    LOG.exception("Too many errors accepting "
                                  "connections: %s" % str(exc))
                    break
                continue  # Pragma: nocover

            # Decrement error count on successful connections
            err_thresh = max(err_thresh - 1, 0)

            # Log the connection attempt
            LOG.info("Accepted connection from %s port %s" %
                     (addr[0], addr[1]))

            # And handle the connection
            eventlet.spawn_n(self.serve, self.connection_class(sock), addr)

        # Close the listening socket
        with utils.ignore_except():
            serv.close()
369677
def port_is_used(port, host='127.0.0.1'):
    
    unused = _can_bind(port, host) and _refuses_connection(port, host)
    return not unused