Picks a free port
196743
def pick_free_port():
        
        test_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        test_socket.bind(('127.0.0.1', 0))
        free_port = int(test_socket.getsockname()[1])
        test_socket.close()
        return free_port
166166
def get_physical_port(self):
        """"""
        obj = None
        if self.is_link_aggregation():
            obj = UnityLinkAggregation.get(self._cli, self.get_id())
        else:
            obj = UnityEthernetPort.get(self._cli, self.get_id())
        return obj
1180258
def pick_unused_ports(num_ports, retry_interval_secs=3, retry_attempts=5):
  """"""
  ports = set()
  for _ in range(retry_attempts):
    ports.update(
        portpicker.pick_unused_port() for _ in range(num_ports - len(ports)))
    ports.discard(None)  # portpicker returns None on error.
    if len(ports) == num_ports:
      return list(ports)
    # Duplicate ports can be returned, especially when insufficient ports are
    # free. Wait for more ports to be freed and retry.
    time.sleep(retry_interval_secs)

  # Could not obtain enough ports. Release what we do have.
  return_ports(ports)

  raise RuntimeError("Unable to obtain %d unused ports." % num_ports)
620584
def get_free_udp_port(self, project):
        
        port = self.find_unused_port(self._udp_port_range[0],
                                     self._udp_port_range[1],
                                     host=self._udp_host,
                                     socket_type="UDP",
                                     ignore_ports=self._used_udp_ports)

        self._used_udp_ports.add(port)
        project.record_udp_port(port)
        log.debug("UDP port {} has been allocated".format(port))
        return port
1294677
def delete_port(self, port):
        '''
        
        '''
        port_id = self._find_port_id(port)
        ret = self.network_conn.delete_port(port=port_id)
        return ret if ret else True
855749
def select_server(self,
                      selector,
                      server_selection_timeout=None,
                      address=None):
        """"""
        return random.choice(self.select_servers(selector,
                                                 server_selection_timeout,
                                                 address))
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
1324664
def client_port(self):
        """"""
        address = self._client.getpeername()
        if isinstance(address, tuple):
            return address[1]

        # Maybe a Unix domain socket connection.
        return 0
476211
def port(self):
        """"""
        self._port = self.lib.iperf_get_test_server_port(self._test)
        return self._port
1355898
function FindFreePortSync(options = {}) {
    this.defaultOptions = {
        // port start for scan
        start: 1,
        // port end for scan
        end: 65534,
        // ports number for scan
        num: 1,
        // specify ip for scan
        ip: '0.0.0.0|127.0.0.1',
        // for inner usage, some platforms like darkwin shows commom address 0.0.0.0:10000 as *.10000
        _ipSpecial: '\\*|127.0.0.1',
        // scan this port
        port: null
    };

    this.msg = {
        error: 'Cannot find free port'
    }

    this.adjustOptions(options);
}
1318118
function () {
    "use strict";

    return new Promise(function (resolve, reject) {
      var numberOfRetries = 5;

      (function retry () {
        var port = 4000 + Math.floor(Math.random() * 1000);
        portscanner.checkPortStatus(port, 'localhost', function (err, status) {
          if (err || status !== 'closed') {
            if (--numberOfRetries > 0) {
              setTimeout(retry);
            } else {
              reject('Cannot find a free port... giving up');
            }
          } else {
            resolve(port);
          }
        });
      })();
    });
  }
457702
def port(self, port=None):
        
        if (port is None) or (port == self.__port):
            return self.__port
        # when port change ensure old socket is close
        self.close()
        # valid port ?
        if 0 < int(port) < 65536:
            self.__port = int(port)
            return self.__port
        else:
            return None
338322
def get_port_for_process(self, pid):
        """"""
        if not self._port_queue:
            raise RuntimeError('No ports being managed.')

        # Avoid an infinite loop if all ports are currently assigned.
        check_count = 0
        max_ports_to_test = len(self._port_queue)
        while check_count < max_ports_to_test:
            # Get the next candidate port and move it to the back of the queue.
            candidate = self._port_queue.pop()
            self._port_queue.appendleft(candidate)
            check_count += 1
            if (candidate.start_time == 0 or
                candidate.start_time != _get_process_start_time(candidate.pid)):
                if _is_port_free(candidate.port):
                    candidate.pid = pid
                    candidate.start_time = _get_process_start_time(pid)
                    if not candidate.start_time:
                        log.info("Can't read start time for pid %d.", pid)
                    self.ports_checked_for_last_request = check_count
                    return candidate.port
                else:
                    log.info(
                        'Port %d unexpectedly in use, last owning pid %d.',
                        candidate.port, candidate.pid)

        log.info('All ports in use.')
        self.ports_checked_for_last_request = check_count
        return 0
588344
def main(argv):
    """"""
    port = pick_unused_port(pid=int(argv[1]) if len(argv) > 1 else None)
    if not port:
        sys.exit(1)
    print(port)
727893
def open_ports(start, end, protocol="TCP"):
    """"""
    _args = ['open-port']
    _args.append('{}-{}/{}'.format(start, end, protocol))
    subprocess.check_call(_args)
801749
def is_valid_port(instance: int):
    """"""
    if not isinstance(instance, (int, str)):
        return True
    return int(instance) in range(65535)
796017
public static int getAvailablePort() {
		for (int i = 0; i < 50; i++) {
			try (ServerSocket serverSocket = new ServerSocket(0)) {
				int port = serverSocket.getLocalPort();
				if (port != 0) {
					return port;
				}
			}
			catch (IOException ignored) {}
		}

		throw new RuntimeException("Could not find a free permitted port on the machine.");
	}