See if a port is available for listening on by trying to listen
on it and seeing if that works or fails.

@param port port to listen to
@return true if the port was available for listening on
486460
public static boolean isPortAvailable(int port) {
        try {
            ServerSocket socket = new ServerSocket(port);
            socket.close();
            return true;
        } catch (IOException e) {
            return false;
        }
    }
736695
public void setPort(int port)
    {
        if (_address == null || _address.getHostName() == null)
            _address= new InetSocketAddress(port);
        else
            _address= new InetSocketAddress(_address.getHostName(), port);
    }
1213122
public boolean bind ()
    {
        // open our TCP listening ports
        int successes = 0;
        for (int port : _ports) {
            try {
                acceptConnections(port);
                successes++;
            } catch (IOException ioe) {
                log.warning("Failure listening to socket", "hostname", _bindHostname,
                            "port", port, ioe);
            }
        }
        return successes > 0;
    }
936727
function onPortSelectInput(newPort) {
			newPort = newPort.replace(/\n/g, ""); newPort = newPort.replace(/\r/g, "");
			var portExists = false;
			for(var i=0; i < ports.length; i++) if(newPort == ports[i].comName) { portExists = true; break; }
			if(!portExists && Number(newPort) && ports[Number(newPort)-1]) {
				newPort = ports[Number(newPort)-1].comName; portExists = true;
			}
			if(portExists) {
				console.log(chalk.bgGreen.black("Listening on port \""+newPort+"\""));
				process.stdin.removeListener('data', onPortSelectInput);
				console.log(); callback(newPort);
			} else {
				console.log(chalk.bgRed.black("Port \""+newPort+"\" does not exist!"));
			}
		}
215190
public static int getAvailablePort(String host, int port, int maxPort) {
        if (isAnyHost(host)
            || isLocalHost(host)
            || isHostInNetworkCard(host)) {
            if (port < MIN_PORT) {
                port = MIN_PORT;
            }
            for (int i = port; i <= maxPort; i++) {
                ServerSocket ss = null;
                try {
                    ss = new ServerSocket();
                    ss.bind(new InetSocketAddress(host, i));
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("ip:{} port:{} is available", host, i);
                    }
                    return i;
                } catch (IOException e) {
                    // continue
                    if (LOGGER.isWarnEnabled()) {
                        LOGGER.warn("Can't bind to address [{}:{}], " +
                            "Maybe 1) The port has been bound. " +
                            "2) The network card of this host is not exists or disable. " +
                            "3) The host is wrong.", host, i);
                    }
                    if (LOGGER.isInfoEnabled()) {
                        LOGGER.info("Begin try next port(auto +1):{}", i + 1);
                    }
                } finally {
                    IOUtils.closeQuietly(ss);
                }
            }
            throw new SofaRpcRuntimeException("Can't bind to ANY port of " + host + ", please check config");
        } else {
            throw new SofaRpcRuntimeException("The host " + host
                + " is not found in network cards, please check config");
        }
    }
638849
public static boolean isUsableLocalPort(int port) {
		if (false == isValidPort(port)) {
			// 给定的IP未在指定端口范围中
			return false;
		}
		try {
			ServerSocketFactory.getDefault().createServerSocket(port, 1, InetAddress.getByName(LOCAL_IP)).close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}
324254
public Yoke listen(int port, @NotNull Handler<Boolean> handler) {
        return listen(port, "0.0.0.0", handler);
    }
1280156
@VisibleForTesting
  static int getNextAvailablePort(InetAddress address, PortAllocator portAllocator) {
    for (int i = 0; i < PORT_MAX_TRIES; i++) {
      int port = portAllocator.getAvailable(address);
      if (isValidPort(port)) {
        PORTS_ALREADY_ALLOCATED.add(port);
        return port;
      }
    }
    throw new IllegalStateException("Fail to find an available port on " + address);
  }
658697
def check_port(self, port):
        
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.bind(("localhost", port))
        except socket.error:
            raise UnityWorkerInUseException(self.worker_id)
        finally:
            s.close()
1238826
def check_port(port, host, timeout=10):
    
    logger.info("trying to open connection to %s:%s", host, port)
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.settimeout(timeout)
        result = sock.connect_ex((host, port))
        logger.info("was connection successful? errno: %s", result)
        if result == 0:
            logger.debug('port is opened: %s:%s' % (host, port))
            return True
        else:
            logger.debug('port is closed: %s:%s' % (host, port))
            return False
    finally:
        sock.close()
1108304
public void setPort(int port) {
    options.get(PORT).setValue(PORT.sanitize(String.valueOf(port)));
  }
872403
public final void waitForPort(final String portName) {
        final Binding binding = getPortBinding(portName);
        waitForPort(binding.getHost(), binding.getPort());
    }
369677
def port_is_used(port, host='127.0.0.1'):
    
    unused = _can_bind(port, host) and _refuses_connection(port, host)
    return not unused
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);
}
362266
def has_port_by_name(self, port_name):
        ''''''
        with self._mutex:
            if self.get_port_by_name(port_name):
                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
1044094
public ServerConfig setPort(int port) {
        if (!NetUtils.isRandomPort(port) && NetUtils.isInvalidPort(port)) {
            throw ExceptionUtils.buildRuntime("server.port", port + "",
                "port must between -1 and 65535 (-1 means random port)");
        }
        this.port = port;
        return this;
    }