Initializes the server socket associated with this end point.

@return ServerSocket
@throws IOException
@throws RetryableChannelException
483633
protected synchronized ServerSocket initServerSocket() throws IOException, RetryableChannelException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "ServerSocket called, new ServerSocket needs to be created");
        }
        TCPChannelConfiguration channelConfig = tcpChannel.getConfig();

        IOException bindError = null;
        BindInfo earlyBind = portBoundEarly(channelConfig.getPort());

        if (earlyBind == null) {
            InetSocketAddress socketAddress = null;

            if (channelConfig.getHostname() == null) {
                socketAddress = new InetSocketAddress((InetAddress) null, channelConfig.getPort());
            } else {
                socketAddress = new InetSocketAddress(channelConfig.getHostname(), channelConfig.getPort());
            }

            if (!socketAddress.isUnresolved()) {
                serverSocket = openServerSocket();

                // receieve buffer size for accepted sockets is set on serverSocket,
                // send buffer size is set on individual sockets

                if ((channelConfig.getReceiveBufferSize() >= TCPConfigConstants.RECEIVE_BUFFER_SIZE_MIN)
                    && (channelConfig.getReceiveBufferSize() <= TCPConfigConstants.RECEIVE_BUFFER_SIZE_MAX)) {
                    serverSocket.setReceiveBufferSize(channelConfig.getReceiveBufferSize());
                }
                if (!channelConfig.getSoReuseAddress()) {
                    //Forced re-use==false custom property
                    try {
                        attemptSocketBind(socketAddress, false);
                    } catch (IOException e) {
                        // no FFDC
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "Forced re-use==false bind attempt failed, ioe=" + e);
                        }
                        bindError = e;
                    }
                } else {
                    //re-use==true (default)
                    // try the standard startup attempts
                    try {
                        attemptSocketBind(socketAddress, false);
                        //If we are not on Windows and the bind succeeded, we should set reuseAddr=true
                        //for future binds.
                        if (!TCPFactoryConfiguration.isWindows()) {
                            this.serverSocket.setReuseAddress(true);
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                Tr.debug(tc, "ServerSocket reuse set to true to allow for later override");
                            }
                        }
                    } catch (IOException ioe) {
                        // See if we got the error because the port is in waiting to be cleaned up.
                        // If so, no one should be accepting connections on it, and open should fail.
                        // If that's the case, we can set ReuseAddr to expedite the bind process.
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "ServerSocket bind failed on first attempt with IOException: " + ioe.getMessage());
                        }
                        bindError = ioe;
                        try {
                            String hostName = channelConfig.getHostname();
                            if (hostName == null) {
                                hostName = "localhost";
                            }
                            InetSocketAddress testAddr = new InetSocketAddress(hostName, channelConfig.getPort());
                            // PK40741 - test for localhost being resolvable before using it
                            if (!testAddr.isUnresolved()) {
                                SocketChannel testChannel = SocketChannel.open(testAddr);
                                // if we get here, socket opened successfully, which means
                                // someone is really listening
                                // so close connection and don't bother trying to bind again
                                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                    Tr.debug(tc, "attempt to connect to port to check listen status worked, someone else is using the port!");
                                }
                                testChannel.close();
                            } else {
                                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                    Tr.debug(tc, "Test connection addr is unresolvable; " + testAddr);
                                }
                            }
                        } catch (IOException testioe) {
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                Tr.debug(tc, "attempt to connect to port to check listen status failed with IOException: " + testioe.getMessage());
                            }
                            try {
                                // open (or close) got IOException, retry with reuseAddr on
                                attemptSocketBind(socketAddress, true);
                                bindError = null;

                            } catch (IOException newioe) {
                                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                    Tr.debug(tc, "ServerSocket bind failed on second attempt with IOException: " + newioe.getMessage());
                                }
                                bindError = newioe;
                            }
                        }
                    }
                }

                if (bindError == null) {
                    // listen port can be different than config port if configed port is '0'
                    listenPort = serverSocket.getLocalPort();
                } else {
                    String displayableHostName = channelConfig.getDisplayableHostname();

                    // add in the exception message to help in problem diagnostics without tracing
                    Tr.error(tc, TCPChannelMessageConstants.BIND_ERROR,
                             new Object[] { channelConfig.getChannelData().getExternalName(), displayableHostName, String.valueOf(channelConfig.getPort()),
                                            bindError.getMessage() });

                    throw new RetryableChannelException(bindError.getMessage());
                }

            } else { // unresolved socket address
                String displayableHostName = channelConfig.getDisplayableHostname();
                Tr.error(tc, TCPChannelMessageConstants.LOCAL_HOST_UNRESOLVED,
                         new Object[] { channelConfig.getChannelData().getExternalName(), displayableHostName, String.valueOf(channelConfig.getPort()) });

                throw new RetryableChannelException(new IOException("local address unresolved"));
            }

        } else {
            // this port was bound earlier by a different service
            Exception e = earlyBind.getBindException();
            if (e == null) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Found early bind, setting serverSocket and listenPort");
                }

                serverSocket = earlyBind.getServerSocket();
                // listen port can be different than config port if configed port is '0'
                listenPort = serverSocket.getLocalPort();
            } else {

                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Early Bind generated the following exception: " + e);
                }

                // add in the exception message to help in problem diagnostics without tracing
                Tr.error(tc, TCPChannelMessageConstants.BIND_ERROR,
                         new Object[] { channelConfig.getChannelData().getExternalName(), earlyBind.getHostname(), String.valueOf(earlyBind.getPort()), e.getMessage() });

                if (e instanceof IOException) {
                    throw (IOException) e;
                }
                if (e instanceof RetryableChannelException) {
                    throw (RetryableChannelException) e;
                }
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "new ServerSocket successfully created");
        }

        return this.serverSocket;
    }
406416
@Override
    public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
        final SSLSocketFactory factory = sslCtxt.getSocketFactory();
        final SSLSocket ss = (SSLSocket) factory.createSocket(address, port, localAddress, localPort);

        ss.setEnabledProtocols(protocols);

        return ss;
    }
1232532
@Override
  public ServerImpl start() throws IOException {
    synchronized (lock) {
      checkState(!started, "Already started");
      checkState(!shutdown, "Shutting down");
      // Start and wait for any ports to actually be bound.

      ServerListenerImpl listener = new ServerListenerImpl();
      for (InternalServer ts : transportServers) {
        ts.start(listener);
        activeTransportServers++;
      }
      executor = Preconditions.checkNotNull(executorPool.getObject(), "executor");
      started = true;
      return this;
    }
  }
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;
    }
357539
public function connect()
    {
        if ($this->connected) {
            return;
        }

        $this->socket = @fsockopen($this->options['hostname'], $this->options['port'], $errno, $errstr, $this->options['timeout']);
        if (!$this->socket) {
            throw new Exception\IOError($errno.' - '.$errstr);
        }

        $this->connected = true;

        return $this;
    }
910775
private function _getSocket()
	{
		if (!isset($this->_socket))
		{
			$this->_socket = new Pheanstalk_Socket_NativeSocket(
				$this->_hostname,
				$this->_port,
				$this->_connectTimeout
			);
		}

		return $this->_socket;
	}
867769
def initialize_socket(uri, opts = {})
      return if opts[:socket]

      @socket = TCPSocket.new(uri.host, uri.port)
      opts.merge!({:socket => @socket})
      @intentional_termination = false
    end
305981
private Socket createSocket() throws IOException {
        final ManagedSocketFactory socketFactory = this.socketBindingManager.getSocketFactory();
        final Socket socket = socketFactory.createSocket(this.name);
        // if the outbound binding specifies the source to use, then bind this socket to the
        // appropriate source
        final SocketAddress sourceSocketAddress = this.getOptionalSourceSocketAddress();
        if (sourceSocketAddress != null) {
            socket.bind(sourceSocketAddress);
        }
        return socket;
    }
716514
public Socket accept() throws IOException{
      Socket s;

      if(!doing_direct){
         if(proxy == null) return null;

         ProxyMessage msg = proxy.accept();
         s = msg.ip == null? new SocksSocket(msg.host,msg.port,proxy)
                                  : new SocksSocket(msg.ip,msg.port,proxy);
         //Set timeout back to 0
         proxy.proxySocket.setSoTimeout(0);
      }else{ //Direct Connection

          //Mimic the proxy behaviour,
          //only accept connections from the speciefed host.
          while(true){
            s = super.accept();
            if(s.getInetAddress().equals(remoteAddr)){
               //got the connection from the right host
               //Close listenning socket.
               break;
            }else
               s.close(); //Drop all connections from other hosts
          }

      }
      proxy = null;
      //Return accepted socket
      return s;
   }
472445
public SocketIOChannel createInboundSocketIOChannel(SocketChannel sc) throws IOException {
        AsyncSocketChannel asc = new AsyncSocketChannel(sc, getAsyncChannelGroup());
        return AioSocketIOChannel.createIOChannel(sc.socket(), asc, this);
    }
374811
public int start() throws IOException {
		synchronized (this.monitor) {
			Assert.state(this.serverThread == null, "Server already started");
			ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
			serverSocketChannel.socket().bind(new InetSocketAddress(this.listenPort));
			int port = serverSocketChannel.socket().getLocalPort();
			logger.trace("Listening for TCP traffic to tunnel on port " + port);
			this.serverThread = new ServerThread(serverSocketChannel);
			this.serverThread.start();
			return port;
		}
	}
721579
protected function guardServerStarting()
    {
        if ($socket = @fsockopen($this->host, $this->port, $errorNumber = 0, $errorString = '', $timeout = 1)) {
            fclose($socket);
            throw new UnableToStartServer($this->host.':'.$this->port);
        }
    }
266029
function createConnection() {

  // create the internal socket object
  var server = new Socket()
    , client = new Socket();

  // pair the sockets
  client.pair = server;
  server.pair = client;

  // register the server side so it is wrapped
  // in a connection and stored as an active connection
  this.connection(server);

  // return the client side of the socket
  return client;
}
529066
public function bindSocket()
    {
        if ($this->erroneous) {
            return false;
        }
        $port = $this->getPort();
        if (!is_int($port)) {
            Daemon::log(get_class($this) . ' (' . get_class($this->pool) . '): no port defined for \'' . $this->uri['uri'] . '\'');
            return;
        }
        if (($port < 1024) && Daemon::$config->user->value !== 'root') {
            $this->listenerMode = false;
        }
        if ($this->listenerMode) {
            $this->setFd($this->host . ':' . $port);
            return true;
        }
        $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if (!$sock) {
            $errno = socket_last_error();
            Daemon::$process->log(get_class($this->pool) . ': Couldn\'t create TCP-socket (' . $errno . ' - ' . socket_strerror($errno) . ').');
            return false;
        }
        if ($this->reuse) {
            if (!socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1)) {
                $errno = socket_last_error();
                Daemon::$process->log(get_class($this->pool) . ': Couldn\'t set option REUSEADDR to socket (' . $errno . ' - ' . socket_strerror($errno) . ').');
                return false;
            }
            if (defined('SO_REUSEPORT') && !@socket_set_option($sock, SOL_SOCKET, SO_REUSEPORT, 1)) {
                $errno = socket_last_error();
                Daemon::$process->log(get_class($this->pool) . ': Couldn\'t set option REUSEPORT to socket (' . $errno . ' - ' . socket_strerror($errno) . ').');
                return false;
            }
        }
        if (!@socket_bind($sock, $this->host, $port)) {
            $errno = socket_last_error();
            Daemon::$process->log(get_class($this->pool) . ': Couldn\'t bind TCP-socket \'' . $this->host . ':' . $port . '\' (' . $errno . ' - ' . socket_strerror($errno) . ').');
            return false;
        }
        socket_getsockname($sock, $this->host, $this->port);
        socket_set_nonblock($sock);
        if (!$this->listenerMode) {
            if (!socket_listen($sock, SOMAXCONN)) {
                $errno = socket_last_error();
                Daemon::$process->log(get_class($this->pool) . ': Couldn\'t listen TCP-socket \'' . $this->host . ':' . $port . '\' (' . $errno . ' - ' . socket_strerror($errno) . ')');
                return false;
            }
        }
        $this->setFd($sock);
        return true;
    }
899107
private function buildSocket()
    {
        $socketDescriptor = sprintf(
            "%s://%s:%d",
            $this->scheme,
            $this->host,
            $this->port
        );

        $socket = @stream_socket_client(
            $socketDescriptor,
            $errNo,
            $errStr,
            $this->connectTimeout,
            \STREAM_CLIENT_CONNECT,
            stream_context_create($this->context)
        );

        if ($socket === false) {
            throw new RuntimeException(
                sprintf(
                    "Failed to create socket-client for %s: %s (%s)",
                    $socketDescriptor,
                    $errStr,
                    $errNo
                )
            );
        }

        // set non-blocking for UDP
        if (strcasecmp("udp", $this->scheme) == 0) {
            stream_set_blocking($socket, 0);
        }

        return $socket;
    }
1157485
public void start() throws IOException {
		// try to automatically retrieve a port
		port = SocketUtils.getNextFreePort(PORT_RANGE_START, PORT_RANGE_END);

		server = SafeCloseSmtpServer.start(port);
	}
158150
protected function createClient()
    {
        /** @var SSLCertificate $credentials */
        $credentials         = $this->getCredentials();
        $url                 = $this->getServiceURL();
        $transport           = !empty($url['transport']) ? $url['transport'] : self::SECURE_TRANSPORT_DEFAULT;

        $this->serviceClient = new SocketClient($url['host'], $url['port']);
        $this->serviceClient
            ->setTransport($transport)
            ->setContextOptions(array(
                'local_cert' => $credentials->getCertificate(),
                'passphrase' => $credentials->getCertificatePassPhrase(),
            ))
            ->addConnectionFlag(STREAM_CLIENT_PERSISTENT)
            ->setBlockingMode(false)
        ;

        return $this;
    }