Get a free port.

@return The free port.
@throws IOException If a free port could not be found.
347104
private static int getOpenPort() throws IOException {
        Log.info(c, "getOpenPort", "Entry.");
        ServerSocket s = new ServerSocket(0);
        Log.info(c, "getOpenPort", "Got socket.");
        int port = s.getLocalPort();
        Log.info(c, "getOpenPort", "Got port " + s);
        s.close();
        Log.info(c, "getOpenPort", "Close socket");
        return port;
    }
821858
protected OutputStream getOutputStream()
        throws IOException
    {
        if (os == null && server != null)
            os = server.writeChannel(channel);

        return os;
    }
119353
public byte[] getBytes() throws IOException {
        InputStream input = getInputStream();
        ByteArrayOutputStream output = new ByteArrayOutputStream();

        final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int len;

        try {
            while ((len = input.read(buffer)) != -1) {
                output.write(buffer, 0, len);
            }
        } finally {
            try {
                output.close();
            } catch (IOException e) {
                // ignore
            }
            try {
                input.close();
            } catch (IOException e) {
                // ignore
            }
        }

        return output.toByteArray();
    }
326604
def pick_free_port(hostname=REDIRECT_HOST, port=0):
    
    import socket
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.bind((hostname, port))  # port=0 finds an open port
    except OSError as e:
        log.warning("Could not bind to %s:%s %s", hostname, port, e)
        if port == 0:
            print('Unable to find an open port for authentication.')
            raise AuthenticationException(e)
        else:
            return pick_free_port(hostname, 0)
    addr, port = s.getsockname()
    s.close()
    return port
1181316
public static int getPort(String uriString) {
        try {
            return (new URI(uriString)).getPort();
        }
        catch (URISyntaxException e) {
            try {
                return (new NetworkInterfaceURI(uriString)).getPort();
            }
            catch (IllegalArgumentException ne) {
                throw new IllegalArgumentException(ne.getMessage(), ne);
            }
        }
    }
333139
public long getFreeMemory() {
    try {
      return (long) mBeanServer.getAttribute(new ObjectName("java.lang", "type", "OperatingSystem"), "FreePhysicalMemorySize");
    } catch (Exception e) {
      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("An exception occurred during memory check", e);
      }
    }
    return -1;
  }
999489
public HttpURLConnection getConnection() throws IOException, ProtocolException {
        HttpURLConnection conn = HttpUtils.getHttpConnection(constructUrl(), expectedResponseCode, allowedUnexpectedResponseCodes, 30, method, headers, streamToWrite);
        return conn;
    }
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.");
	}
54604
def port(self, check=False):
        
        if not self.__ports:  # refresh ports if sequence is empty
            self.refresh()

        try:
            port = self.__ports.pop()
            if check:
                while not self.__check_port(port):
                    self.release_port(port)
                    port = self.__ports.pop()
        except (IndexError, KeyError):
            raise IndexError("Could not find a free port,\nclosed ports: {closed}".format(closed=self.__closed))
        self.__closed.add(port)
        return port
730201
protected HttpURLConnection generateConn() throws IOException {
        HttpURLConnection conn;
        conn = (HttpURLConnection) new URL(url).openConnection();
        return conn;
    }
380197
public BufferedOutputStream getOutputStream() throws IORuntimeException {
		try {
			return new BufferedOutputStream(new FileOutputStream(FileUtil.touch(file)));
		} catch (IOException e) {
			throw new IORuntimeException(e);
		}
	}
1026783
public int available() throws IOException {
        checkForClosed();
        return (int) Math.min(_file.length() - _offset + bytesLeftInBuffer(), Integer.MAX_VALUE);
    }
1158325
public T obtain () {
		T object = freeObjects.poll();
		return object != null ? object : create();
	}
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
1198963
public T allocate()
  {
    T value = _freeRing.allocate();
    
    if (value != null) {
      return value;
    }
    
    return _freeRingSoft.allocate();
  }
602101
public ServerSocket socket() throws IOException {
        final String port = this.map.get("port");
        if (port == null) {
            throw new IllegalArgumentException("--port must be specified");
        }
        final ServerSocket socket;
        if (port.matches("\\d+")) {
            socket = new ServerSocket(Integer.parseInt(port));
        } else {
            final File file = new File(port);
            if (file.exists()) {
                try (Reader reader = new Utf8InputStreamContent(
                    Files.newInputStream(file.toPath())
                    )
                ) {
                    // @checkstyle MagicNumber (1 line)
                    final char[] chars = new char[8];
                    final int length = reader.read(chars);
                    socket = new ServerSocket(
                        Integer.parseInt(new String(chars, 0, length))
                    );
                }
            } else {
                socket = new ServerSocket(0);
                try (Writer writer = new Utf8OutputStreamContent(
                    Files.newOutputStream(file.toPath())
                )) {
                    writer.append(Integer.toString(socket.getLocalPort()));
                }
            }
        }
        return socket;
    }
1128068
def get_unused_port(port=None):
    """"""
    if port is None or port < 1024 or port > 65535:
        port = random.randint(1024, 65535)
    assert(1024 <= port <= 65535)
    while True:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.bind(('', port))  # Try to open port
        except socket.error as e:
            if e.errno in (98, 10048):  # 98, 10048 means address already bound
                return get_unused_port(None)
            raise e
        s.close()
        return port