Accepts xmlsocket requests on <code>socketPolicyPort</code> and responds any host may
connect to any port on this host.
161734
public void init (int socketPolicyPort)
    {
        _acceptor =
            new ServerSocketChannelAcceptor(null, new int[] { socketPolicyPort }, this);

        // build the XML once and for all
        StringBuilder policy = new StringBuilder()
            .append("<?xml version=\"1.0\"?>\n")
            .append("<cross-domain-policy>\n");
        // if we're running on 843, serve a master policy file
        if (socketPolicyPort == MASTER_PORT) {
            policy.append("  <site-control permitted-cross-domain-policies=\"master-only\"/>\n");
        }

        policy.append("  <allow-access-from domain=\"*\" to-ports=\"*\"/>\n");
        policy.append("</cross-domain-policy>\n\n");

        try {
            _policy = policy.toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException("UTF-8 encoding missing; this vm is broken", e);
        }
        start();
    }
87959
private SocketChannel accept() throws IOException
    {
        //  The situation where connection cannot be accepted due to insufficient
        //  resources is considered valid and treated by ignoring the connection.
        //  Accept one connection and deal with different failure modes.
        assert (fd != null);

        SocketChannel sock = fd.accept();

        if (!options.tcpAcceptFilters.isEmpty()) {
            boolean matched = false;
            for (TcpAddress.TcpAddressMask am : options.tcpAcceptFilters) {
                if (am.matchAddress(address.address())) {
                    matched = true;
                    break;
                }
            }
            if (!matched) {
                try {
                    sock.close();
                }
                catch (IOException e) {
                }
                return null;
            }
        }
        if (options.tos != 0) {
            TcpUtils.setIpTypeOfService(sock, options.tos);
        }
        //  Set the socket buffer limits for the underlying socket.
        if (options.sndbuf != 0) {
            TcpUtils.setTcpSendBuffer(sock, options.sndbuf);
        }
        if (options.rcvbuf != 0) {
            TcpUtils.setTcpReceiveBuffer(sock, options.rcvbuf);
        }

        if (!isWindows) {
            TcpUtils.setReuseAddress(sock, true);
        }

        return sock;
    }
277054
private void listen(Address address, Consumer<Connection> listener, ThreadContext context) {
    channelGroup = new DefaultChannelGroup("catalyst-acceptor-channels", GlobalEventExecutor.INSTANCE);

    handler = new ServerHandler(connections, listener, context, transport.properties());

    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(transport.eventLoopGroup())
      .channel(NioServerSocketChannel.class)
      .handler(new LoggingHandler(LogLevel.DEBUG))
      .childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel channel) throws Exception {
          ChannelPipeline pipeline = channel.pipeline();
          if (transport.properties().sslEnabled()) {
            pipeline.addFirst(new SslHandler(new NettyTls(transport.properties()).initSslEngine(false)));
          }
          pipeline.addLast(FIELD_PREPENDER);
          pipeline.addLast(new LengthFieldBasedFrameDecoder(transport.properties().maxFrameSize(), 0, 4, 0, 4));
          pipeline.addLast(handler);
        }
      })
      .option(ChannelOption.SO_BACKLOG, transport.properties().acceptBacklog())
      .option(ChannelOption.TCP_NODELAY, transport.properties().tcpNoDelay())
      .option(ChannelOption.SO_REUSEADDR, transport.properties().reuseAddress())
      .childOption(ChannelOption.ALLOCATOR, ALLOCATOR)
      .childOption(ChannelOption.SO_KEEPALIVE, transport.properties().tcpKeepAlive());

    if (transport.properties().sendBufferSize() != -1) {
      bootstrap.childOption(ChannelOption.SO_SNDBUF, transport.properties().sendBufferSize());
    }
    if (transport.properties().receiveBufferSize() != -1) {
      bootstrap.childOption(ChannelOption.SO_RCVBUF, transport.properties().receiveBufferSize());
    }

    LOGGER.info("Binding to {}", address);

    ChannelFuture bindFuture = bootstrap.bind(address.socketAddress());
    bindFuture.addListener((ChannelFutureListener) channelFuture -> {
      if (channelFuture.isSuccess()) {
        listening = true;
        context.executor().execute(() -> {
          LOGGER.info("Listening at {}", bindFuture.channel().localAddress());
          listenFuture.complete(null);
        });
      } else {
        context.execute(() -> listenFuture.completeExceptionally(channelFuture.cause()));
      }
    });
    channelGroup.add(bindFuture.channel());
  }
629174
def serve_service_on_host_and_port(host, port)
      # log information
      logger.info('Running service on ' + (host == '' ? '<any>' : host) + ':' + port.to_s)
      # instantiate the service for host and port
      # if host is empty "" wildcard (all) interfaces are used
      # otherwise it will be bind to single host ip only
      tcp_server = TCPServer.new(host, port)
      # append this server to the list of TCPServers
      @tcp_servers << tcp_server

      # run thread until shutdown
      @tcp_server_threads << Thread.new do
        begin
          # always check for shutdown request
          until shutdown?
            # get new client and start additional thread
            # to handle client process
            client = tcp_server.accept
            Thread.new(client) do |io|
              # add to list of connections
              @connections << Thread.current
              # handle connection
              begin
                # initialize a session storage hash
                Thread.current[:session] = {}
                # process smtp service on io socket
                io = serve_client(Thread.current[:session], io)
                # save returned io value due to maybe
                # established ssl io socket
              rescue SmtpdStopConnectionException
                # ignore this exception due to service shutdown
              rescue StandardError => e
                # log fatal error while handling connection
                logger.fatal(e.backtrace.join("\n"))
              ensure
                begin
                  # always gracefully shutdown connection.
                  # if the io object was overriden by the
                  # result from serve_client() due to ssl
                  # io, the ssl + io socket will be closed
                  io.close
                rescue StandardError
                  # ignore any exception from here
                end
                # remove closed session from connections
                @connections_mutex.synchronize do
                  # drop this thread from connections
                  @connections.delete(Thread.current)
                  # drop this thread from processings
                  @processings.delete(Thread.current)
                  # signal mutex for next waiting thread
                  @connections_cv.signal
                end
              end
            end
          end
        rescue SmtpdStopServiceException
          # ignore this exception due to service shutdown
        rescue StandardError => e
          # log fatal error while starting new thread
          logger.fatal(e.backtrace.join("\n"))
        ensure
          begin
            # drop the service
            tcp_server.close
            # remove from list
            @tcp_servers.delete(tcp_server)
            # reset local var
            tcp_server = nil
          rescue StandardError
            # ignor any error from here
          end
          if shutdown?
            # wait for finishing opened connections
            @connections_mutex.synchronize do
              @connections_cv.wait(@connections_mutex) until @connections.empty?
            end
          else
            # drop any open session immediately
            @connections.each { |c| c.raise SmtpdStopConnectionException }
          end
          # remove this thread from list
          @tcp_server_threads.delete(Thread.current)
        end
      end
    end
518957
private static boolean isPortOpen(InetAddress pAddress, int pPort) {
        Socket socket = null;
        try {
            socket = new Socket();
            socket.setReuseAddress(true);
            SocketAddress sa = new InetSocketAddress(pAddress, pPort);
            socket.connect(sa, 200);
            return socket.isConnected();
        } catch (IOException e) {
            return false;
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // Best effort. Hate that close throws an IOException, btw. Never saw a real use case for that.
                }
            }
        }
    }
789332
function shouldProxy(hostname, port) {
  var NO_PROXY = getEnv('no_proxy').toLowerCase();
  if (!NO_PROXY) {
    return true;  // Always proxy if NO_PROXY is not set.
  }
  if (NO_PROXY === '*') {
    return false;  // Never proxy if wildcard is set.
  }

  return NO_PROXY.split(/[,\s]/).every(function(proxy) {
    if (!proxy) {
      return true;  // Skip zero-length hosts.
    }
    var parsedProxy = proxy.match(/^(.+):(\d+)$/);
    var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy;
    var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0;
    if (parsedProxyPort && parsedProxyPort !== port) {
      return true;  // Skip if ports don't match.
    }

    if (!/^[.*]/.test(parsedProxyHostname)) {
      // No wildcards, so stop proxying if there is an exact match.
      return hostname !== parsedProxyHostname;
    }

    if (parsedProxyHostname.charAt(0) === '*') {
      // Remove leading wildcard.
      parsedProxyHostname = parsedProxyHostname.slice(1);
    }
    // Stop proxying if the hostname ends with the no_proxy host.
    return !stringEndsWith.call(hostname, parsedProxyHostname);
  });
}
621886
public static String authorityFromHostAndPort(String host, int port) {
    try {
      return new URI(null, null, host, port, null, null, null).getAuthority();
    } catch (URISyntaxException ex) {
      throw new IllegalArgumentException("Invalid host or port: " + host + " " + port, ex);
    }
  }
416796
static <V extends VersionedProtocol> V waitForProxy(Class<V> protocol, InetSocketAddress addr,
			long timeout) throws IOException {
		long startTime = System.currentTimeMillis();
		IOException ioe;
		while (true) {
			try {
				return getProxy(protocol, addr);
			} catch (ConnectException se) { // namenode has not been started
				LOG.info("Server at " + addr + " not available yet, Zzzzz...");
				ioe = se;
			} catch (SocketTimeoutException te) { // namenode is busy
				LOG.info("Problem connecting to server: " + addr);
				ioe = te;
			}
			// check if timed out
			if (System.currentTimeMillis() - timeout >= startTime) {
				throw ioe;
			}

			// wait for retry
			try {
				Thread.sleep(1000);
			} catch (InterruptedException ie) {
				// IGNORE
			}
		}
	}
370290
private void handshake() throws WebSocketException
    {
        try
        {
            // Perform handshake with the proxy server.
            mProxyHandshaker.perform();
        }
        catch (IOException e)
        {
            // Handshake with the proxy server failed.
            String message = String.format(
                "Handshake with the proxy server (%s) failed: %s", mAddress, e.getMessage());

            // Raise an exception with PROXY_HANDSHAKE_ERROR.
            throw new WebSocketException(WebSocketError.PROXY_HANDSHAKE_ERROR, message, e);
        }

        if (mSSLSocketFactory == null)
        {
            // SSL handshake with the WebSocket endpoint is not needed.
            return;
        }

        try
        {
            // Overlay the existing socket.
            mSocket = mSSLSocketFactory.createSocket(mSocket, mHost, mPort, true);
        }
        catch (IOException e)
        {
            // Failed to overlay an existing socket.
            String message = "Failed to overlay an existing socket: " + e.getMessage();

            // Raise an exception with SOCKET_OVERLAY_ERROR.
            throw new WebSocketException(WebSocketError.SOCKET_OVERLAY_ERROR, message, e);
        }

        try
        {
            // Start the SSL handshake manually. As for the reason, see
            // http://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/samples/sockets/client/SSLSocketClient.java
            ((SSLSocket)mSocket).startHandshake();

            if (mSocket instanceof SSLSocket)
            {
                // Verify that the proxied hostname matches the certificate here since
                // this is not automatically done by the SSLSocket.
                verifyHostname((SSLSocket)mSocket, mProxyHandshaker.getProxiedHostname());
            }
        }
        catch (IOException e)
        {
            // SSL handshake with the WebSocket endpoint failed.
            String message = String.format(
                "SSL handshake with the WebSocket endpoint (%s) failed: %s", mAddress, e.getMessage());

            // Raise an exception with SSL_HANDSHAKE_ERROR.
            throw new WebSocketException(WebSocketError.SSL_HANDSHAKE_ERROR, message, e);
        }
    }
433600
public Socket getSocket(String host, int port, boolean useSecureSocket, SecurityDomain securityDomain) throws Exception {
		return getSocket(host,port,useSecureSocket,securityDomain,null);
	}
792765
@Override
    public Socket createSocket(String host, int port) throws IOException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, "SocketFactory attempting to create socket for host: " + host + " port: " + port);

        // check for SSL addresses
        if (Util.isEncodedHost(host, HOST_PROTOCOL)) {
            String sslConfigName = Util.decodeHostInfo(host);
            host = Util.decodeHost(host);
            return createSSLSocket(host, (char) port, sslConfigName);
        } else {
            return createPlainSocket(host, port);
        }
    }
155307
public static WebsocketServerTransport create(int port) {
    HttpServer httpServer = HttpServer.create().port(port);
    return create(httpServer);
  }
518816
private void doAccept() throws IOException{
      Socket s;
      long startTime = System.currentTimeMillis();

      while(true){
         s = ss.accept();
         if(s.getInetAddress().equals(msg.ip)){
            //got the connection from the right host
            //Close listenning socket.
            ss.close();
            break;
         }else if(ss instanceof SocksServerSocket){
            //We can't accept more then one connection
            s.close();
            ss.close();
            throw new SocksException(Proxy.SOCKS_FAILURE);
         }else{
            if(acceptTimeout!=0){ //If timeout is not infinit
               int newTimeout = acceptTimeout-(int)(System.currentTimeMillis()-
                                                           startTime);
               if(newTimeout <= 0) throw new InterruptedIOException(
                                "In doAccept()");
               ss.setSoTimeout(newTimeout);
            }
            s.close(); //Drop all connections from other hosts
         }
      }

      //Accepted connection
      remote_sock = s;
      remote_in = s.getInputStream();
      remote_out = s.getOutputStream();

      //Set timeout
      remote_sock.setSoTimeout(iddleTimeout);

      log("Accepted from "+s.getInetAddress()+":"+s.getPort());

      ProxyMessage response;

      if(msg.version == 5)
         response = new Socks5Message(Proxy.SOCKS_SUCCESS, s.getInetAddress(),
                                                           s.getPort());
      else
         response = new Socks4Message(Socks4Message.REPLY_OK,
                                      s.getInetAddress(), s.getPort());
      response.write(out);
   }
911970
private SocketChannel connect( URI transportURI ) throws PacketTransportException
    {
        String host = transportURI.getHost();
        int port = transportURI.getPort();
        
        try
        {
        	SocketChannel socketChannel = SocketChannel.open();
        	socketChannel.configureBlocking(false);
        	SocketUtils.setupSocket(socketChannel.socket(),
        			                socketSendBufferSize,
        			                socketRecvBufferSize);
        	        	
            log.debug("#"+id+" opening a TCP connection to "+host+":"+port);
            socketChannel.connect(new InetSocketAddress(host,port));
            
            return socketChannel;
        }
        catch (Exception e)
        {
            log.error("#"+id+" could not connect to "+host+":"+port,e);
            throw new PacketTransportException("Could not connect to "+host+":"+port+" : "+e.toString());
        }
    }
251259
private boolean portAvailable(final int port) {
    ServerSocket socket = null;
    try {
      socket = new ServerSocket(port);
      return true;
    } catch (IOException ignored) {
      return false;
    } finally {
      if (socket != null) {
        try {
          socket.close();
        } catch (IOException e) {
          log.error("Couldn't close socket on port {} when checking availability: {}", port, e);
        }
      }
    }
  }
194700
def get_connection(self, host, port):
        
        return beanstalkc.Connection(
            host=host,
            port=port
        )
781533
public static Proxy socksProxy(String host, int port) {
        return new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(Objects.requireNonNull(host), port));
    }