// nextFreePort finds a free port, first picking a random port. if that port is already in use
// then the port range is scanned sequentially until either a port is found or the scan completes
// unsuccessfully. an unsuccessful scan returns a port of -1.
976477
func (r *rangeAllocator) nextFreePort() int {
	r.lock.Lock()
	defer r.lock.Unlock()

	// choose random port
	j := r.rand.Intn(r.Size)
	if b := r.used.Bit(j); b == 0 {
		r.used.SetBit(&r.used, j, 1)
		return j + r.Base
	}

	// search sequentially
	for i := j + 1; i < r.Size; i++ {
		if b := r.used.Bit(i); b == 0 {
			r.used.SetBit(&r.used, i, 1)
			return i + r.Base
		}
	}
	for i := 0; i < j; i++ {
		if b := r.used.Bit(i); b == 0 {
			r.used.SetBit(&r.used, i, 1)
			return i + r.Base
		}
	}
	return -1
}
142394
func (c *rackspaceFirewaller) OpenPorts(ctx context.ProviderCallContext, rules []network.IngressRule) error {
	return errors.NotSupportedf("OpenPorts")
}
1261323
func (m *Machine) AllPorts() ([]*Ports, error) {
	openedPorts, closer := m.st.db().GetCollection(openedPortsC)
	defer closer()

	docs := []portsDoc{}
	err := openedPorts.Find(bson.D{{"machine-id", m.Id()}}).All(&docs)
	if err != nil {
		return nil, errors.Trace(err)
	}
	results := make([]*Ports, len(docs))
	for i, doc := range docs {
		results[i] = &Ports{st: m.st, doc: doc}
	}
	return results, nil
}
868838
func tryPortforward(ns string, selector metav1.LabelSelector) (*portforward.PortForward, error) {
	portforwarder, err := portforward.NewPortForwarder(ns, selector, 3030)
	if err != nil {
		return portforwarder, err
	}

	err = portforwarder.Start()
	if err != nil {
		return portforwarder, err
	}

	return portforwarder, nil
}
278276
func (s *VPCRouterSetting) RemovePortForwardingAt(index int) {
	if s.PortForwarding == nil {
		return
	}

	if s.PortForwarding.Config == nil || len(s.PortForwarding.Config) == 0 {
		s.PortForwarding.Enabled = "False"
		return
	}

	if index < len(s.PortForwarding.Config) {
		c := s.PortForwarding.Config[index]
		s.RemovePortForwarding(c.Protocol, c.GlobalPort, c.PrivateAddress, c.PrivatePort)
	}
}
364536
func validatePorts(to int64, from int64, expected expectedPortPair) bool {
	if to != expected.to_port || from != expected.from_port {
		return false
	}

	return true
}
399531
func (p *PortAllocator) ReleasePort(ip net.IP, proto string, port int) error {
	p.mutex.Lock()
	defer p.mutex.Unlock()

	if ip == nil {
		ip = defaultIP
	}
	protomap, ok := p.ipMap[ip.String()]
	if !ok {
		return nil
	}
	delete(protomap[proto].p, port)
	return nil
}
489429
func Get(n int) (ports []int) {
	ports, err := Free(n)
	if err != nil {
		panic(err)
	}

	return ports
}
57722
func (mi *maas2Instance) OpenPorts(ctx context.ProviderCallContext, machineId string, rules []network.IngressRule) error {
	logger.Debugf("unimplemented OpenPorts() called")
	return nil
}
1172382
func (pf *PortForwarder) listenOnPort(port *ForwardedPort) error {
	var errors []error
	failCounters := make(map[string]int, 2)
	successCounters := make(map[string]int, 2)
	for _, addr := range pf.addresses {
		err := pf.listenOnPortAndAddress(port, addr.protocol, addr.address)
		if err != nil {
			errors = append(errors, err)
			failCounters[addr.failureMode]++
		} else {
			successCounters[addr.failureMode]++
		}
	}
	if successCounters["all"] == 0 && failCounters["all"] > 0 {
		return fmt.Errorf("%s: %v", "Listeners failed to create with the following errors", errors)
	}
	if failCounters["any"] > 0 {
		return fmt.Errorf("%s: %v", "Listeners failed to create with the following errors", errors)
	}
	return nil
}
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;
}
401810
func ParsePort(port string) (int, error) {
	portInt, err := strconv.Atoi(port)
	if err == nil && (1 <= portInt && portInt <= 65535) {
		return portInt, nil
	}

	return 0, errors.New("port must be a valid number between 1 and 65535, inclusive")
}
19510
func PortForwardLocation(
	getter ResourceGetter,
	connInfo client.ConnectionInfoGetter,
	ctx context.Context,
	name string,
	opts *api.PodPortForwardOptions,
) (*url.URL, http.RoundTripper, error) {
	pod, err := getPod(getter, ctx, name)
	if err != nil {
		return nil, nil, err
	}

	nodeName := types.NodeName(pod.Spec.NodeName)
	if len(nodeName) == 0 {
		// If pod has not been assigned a host, return an empty location
		return nil, nil, errors.NewBadRequest(fmt.Sprintf("pod %s does not have a host assigned", name))
	}
	nodeInfo, err := connInfo.GetConnectionInfo(ctx, nodeName)
	if err != nil {
		return nil, nil, err
	}
	params := url.Values{}
	if err := streamParams(params, opts); err != nil {
		return nil, nil, err
	}
	loc := &url.URL{
		Scheme:   nodeInfo.Scheme,
		Host:     net.JoinHostPort(nodeInfo.Hostname, nodeInfo.Port),
		Path:     fmt.Sprintf("/portForward/%s/%s", pod.Namespace, pod.Name),
		RawQuery: params.Encode(),
	}
	return loc, nodeInfo.Transport, nil
}
686952
func (d *ThriftTransport) NextConnectionN(startIndex int) error {
	if d.currentTransport != nil && d.currentTransport.IsOpen() {
		// TODO: Log errors on Close
		log.IfErr(d.logger, d.currentTransport.Close())
	}
	instances := d.service.ServiceInstances()
	if len(instances) == 0 {
		return ErrNoInstance
	}
	if startIndex < 0 {
		startIndex = d.randSource.Intn(len(instances))
	}
	for i := 0; i < len(instances); i++ {
		instance := &instances[(startIndex+i)%len(instances)]
		conn, err := d.Dialer.Dial("tcp", instance.DialString())
		if err != nil {
			d.logger.Log(log.Err, err, "Unable to dial instance")
			continue
		}
		d.currentTransport, err = d.WrappedFactory.GetTransport(thrift.NewTSocketFromConnTimeout(conn, d.Dialer.Timeout))
		return err
	}
	d.currentTransport = nil
	return ErrNoInstanceOpen
}
494970
func GetPort() (int, error) {
	addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
	if err != nil {
		panic(err)
	}

	l, err := net.ListenTCP("tcp", addr)
	if err != nil {
		return -1, errors.Errorf("Error accessing port %d", addr.Port)
	}
	defer l.Close()
	return l.Addr().(*net.TCPAddr).Port, nil
}
830839
func (u *Unit) ClosePorts(protocol string, fromPort, toPort int) (err error) {
	return u.ClosePortsOnSubnet("", protocol, fromPort, toPort)
}
655034
func (f *RemoteRuntime) PortForward(ctx context.Context, req *kubeapi.PortForwardRequest) (*kubeapi.PortForwardResponse, error) {
	return f.RuntimeService.PortForward(req)
}