### functon reservedPort #### @desired {Number} Desired port to bind to. Helper function which will emit an error if the server (the `this` argument) is in `carapace.ports.throw`
192873
function reservedPort(desired) {
  if (carapace.ports.throw.indexOf(desired) !== -1) {
    this.close();
    //
    // Build fake error
    //
    var err = new Error('EADDRINUSE, Address already in use');
    err.code = 'EADDRINUSE';
    err.syscall = 'bind';
    err.errno = 100;
    this.emit('error', err);
    return true;
  }
  
  return false;
}
834910
def validate_port(port):
    ''''''
    if not isinstance(port, (str, int)):
        raise TypeError(f'port must be an integer or string: {port}')
    if isinstance(port, str) and port.isdigit():
        port = int(port)
    if isinstance(port, int) and 0 < port <= 65535:
        return port
    raise ValueError(f'invalid port: {port}')
941141
function errnoException(err, syscall, address, port) {
		var errname;
		var message;
		if ((typeof err === 'undefined' ? 'undefined' : _typeof(err)) == 'object') {
			errname = errorCodes[err.number] || err.number;
			message = syscall + ' ' + errname + ' ' + err.message;
		} else {
			errname = err;
			message = syscall + ' ' + errname;
		}
		var e = new Error(message);
		e.code = e.errno = errname;
		e.syscall = syscall;
		if (port) {
			e.port = port;
		}
		if (address) {
			e.address = address;
		}
		return e;
	}
408121
def portMapping(nport,proto)
            checkProto(proto)
            checkPort(nport)
            if nport.to_i == 0 then
                raise ArgumentError, "Port must be an int value and greater then 0."
            end
            joinThread()
            client = getCString()
            lport = getCString()
            if MiniUPnP.UPNP_GetSpecificPortMappingEntry(@urls.controlURL,
                                     @data.servicetype, nport.to_s,proto,
                                     client,lport) != 0 then
                raise UPnPException.new, "Error while retriving the port mapping."
            end
            return client.rstrip, lport.rstrip.to_i
        end
802479
function findPort(cb) {
    var port = tryPort;
    tryPort += 1;

    var server = net.createServer();
    server.listen(port, function(err) {
        server.once('close', function() {
            cb(port);
        });
        server.close();
    });
    server.on('error', function(err) {
        log("port " + tryPort + " is occupied");
        findPort(cb);
    });
}
939078
function isLegalPort(port: number) : boolean {
  if (typeof port === 'string' && port.trim() === '') {
    return false;
  }
  return +port === (port >>> 0) && port >= 0 && port <= 0xFFFF;
}
781510
function checkPort(port, host, callback) {
    var socket = new Socket(),
        status = null;
    socket.on('connect', () => {
        status = 'open';
        socket.end();
    });
    socket.setTimeout(1500);
    socket.on('timeout', () => {
        status = 'closed';
        socket.destroy();
    });
    socket.on('error', (exception) => {
        status = 'closed';
    });
    socket.on('close', (exception) => {
        callback(null, status,host,port);
    });
    socket.connect(port, host);
}
369677
def port_is_used(port, host='127.0.0.1'):
    
    unused = _can_bind(port, host) and _refuses_connection(port, host)
    return not unused
861955
async function resolvePort (port) {
  const portfinder = require('portfinder')
  portfinder.basePort = parseInt(port) || 8080
  port = await portfinder.getPortPromise()
  return port
}
1235409
def bind(endpoint)
      rc = ffi_delegate.bind("%s", :string, endpoint)
      raise_zmq_err("unable to bind to %p" % endpoint) if rc == -1
      @last_tcp_port = rc if rc > 0
    end
517403
function getPort(req) {
		if (req.connection && req.connection.localPort) {
			return req.connection.localPort.toString();
		}
		const host = req.headers && req.headers.host;
		let protocolSrc = 80;
		if (host && ((host.match(/:/g) || []).length) === 1) {
			const possiblePort = host.split(':')[1];
			protocolSrc = isNaN(possiblePort) ? protocolSrc : possiblePort;
		}
		return protocolSrc;
	}
1167074
function isAvailable(port) {
    return new Promise((resolve, reject) => {
        const server = net.createServer();

        server.unref();
        server.on('error', reject);
        const options = {};
        options.port = port;
        server.listen(options, () => {
            const { port } = server.address();
            server.close(() => {
                resolve(port);
            });
        });
    });
}
904538
def checkPortAvailable(ha):
    """"""
    # Not sure why OS would allow binding to one type and not other.
    # Checking for port available for TCP and UDP.
    sockTypes = (socket.SOCK_DGRAM, socket.SOCK_STREAM)
    for typ in sockTypes:
        sock = socket.socket(socket.AF_INET, typ)
        try:
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.bind(ha)
            if typ == socket.SOCK_STREAM:
                l_onoff = 1
                l_linger = 0
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
                                struct.pack('ii', l_onoff, l_linger))
        except OSError as exc:
            if exc.errno in [
                errno.EADDRINUSE, errno.EADDRNOTAVAIL,
                WS_SOCKET_BIND_ERROR_ALREADY_IN_USE,
                WS_SOCKET_BIND_ERROR_NOT_AVAILABLE
            ]:
                raise PortNotAvailable(ha)
            else:
                raise exc
        finally:
            sock.close()
203324
function (host, port, onError) {
	
	var proxy = undefined;
	
	var options = {target: 'ws://' + host, ws: true};
	LOG.warn('create new ws proxy at port: ' + port + ' options: ', 'SR.Proxy');
	LOG.warn(options, 'SR.Proxy');
	
	proxy = httpProxy.createServer(options);
		
	// install error handler (NOTE: very imporant for stability)
	proxy.on('error', function (err, req, res) {
		UTIL.safeCall(onError, err);
	});
	
	// be notified when closed
	// ref: https://github.com/nodejitsu/node-http-proxy
	proxy.on('close', function (req, socket, head) {
  		// view disconnected websocket connections
  		console.log('Client disconnected');
	});	

	// store proxy for later uses
	// NOTE: not used directly
	l_proxies[host] = proxy;

	// record local port for future references
	// NOTE: this is an important step for future queries of the proxy
	// and may need to be performed before setting the on('xx') handler(s) 
	// BUG: seems like 'local_port' info will disappear under certain circumstances
	// (after entries are shutdown & restart many times)
	l_proxies[host].local_port = port;
		
	// start to listen for requests	
	// NOTE: listen may fail or cause errors that could trigger this proxy be removed from list
	proxy.listen(port);	

	return proxy;
	
	/* 2nd version
	proxy = httpProxy.createProxyServer(options);
	
	proxy.on('error', function (e) {
		UTIL.safeCall(onError, e);
	});
	
	// start a new HTTP server just for websocket connections
	var proxyServer = http.createServer(function (req, res) {
		LOG.warn('incoming request to standalone HTTP ws proxy', 'SR.Proxy');
		proxy.web(req, res);
	});

	//
	// Listen to the `upgrade` event and proxy the
	// WebSocket requests as well.
	//
	proxyServer.on('upgrade', function (req, socket, head) {
		try {
			proxy.ws(req, socket, head);
		}
	    catch (e) {
			LOG.error('websocket error:', 'SR.Proxy');
			LOG.error(e, 'SR.Proxy');
		}
			
	});

	// TODO: may need to provide a unique port for it
	// TODO: record this http server?
	LOG.warn('starting ws proxy at port: ' + port, 'SR.Proxy');
	proxyServer.listen(port);
	
	return proxy;
	*/
}
457190
def reserve(self, force=False):
        

        p_reservation = self.get_attribute('p_reservation')
        if p_reservation == 'RESERVED_BY_YOU':
            return
        elif p_reservation == 'RESERVED_BY_OTHER' and not force:
            raise TgnError('Port {} reserved by {}'.format(self, self.get_attribute('p_reservedby')))
        self.relinquish()
        self.send_command('p_reservation', 'reserve')
513677
def allow_port(port, proto='tcp', direction='both'):
    '''
    
    '''

    ports = get_ports(proto=proto, direction=direction)
    direction = direction.upper()
    _validate_direction_and_proto(direction, proto)
    directions = build_directions(direction)
    results = []
    for direction in directions:
        _ports = ports[direction]
        _ports.append(port)
        results += allow_ports(_ports, proto=proto, direction=direction)
    return results
989971
def _get_valid_port(self, port):
        
        if '/' in port:
            port, protocol = port.split('/')
        else:
            protocol = 'tcp'

        try:
            int(port)
        except ValueError:
            raise ValueError("{0} isn't a valid port number.".format(port))

        if protocol not in ('tcp', 'udp'):
            raise ValueError("exposed ports only supports udp or tcp. {0} was passed".format(protocol))

        return "{0}/{1}".format(port, protocol)