Example usage for java.net Socket getPort

List of usage examples for java.net Socket getPort

Introduction

In this page you can find the example usage for java.net Socket getPort.

Prototype

public int getPort() 

Source Link

Document

Returns the remote port number to which this socket is connected.

Usage

From source file:org.zaproxy.zap.extension.websocket.WebSocketProxy.java

/**
 * Create a WebSocket on a channel. You need to call {@link
 * WebSocketProxy#startListeners(ExecutorService, InputStream)} to turn on this proxy.
 *
 * @param localSocket Channel from local machine to ZAP.
 * @param remoteSocket Channel from ZAP to remote/target machine.
 * @see #WebSocketProxy(Socket, Socket, String, int)
 *///from  ww  w  . j a  v  a  2  s. c  o m
public WebSocketProxy(Socket localSocket, Socket remoteSocket) {
    this(localSocket, remoteSocket, remoteSocket.getInetAddress().getHostName(), remoteSocket.getPort());
}

From source file:org.rifidi.emulator.io.comm.ip.tcpserver.TCPServerCommunicationIncomingConnectionHandler.java

/**
 * The main logic of this monitor, which creates a new server socket bound
 * to the current local IP / port combination and listens for clients to
 * connect until explictly unbound./*from w w  w . ja  v a  2s.co m*/
 * 
 * @see java.lang.Runnable#run()
 */
public void run() {
    logger.debug("Attempting to create TCPServer...");

    /* Create the ServerSocket and check to see 
     * if the server socket was made successfully */

    hasNoError = bindServerSocket();

    if (hasNoError) {
        logger.debug("No error creating server, proceeding.");

        /* A string which will be used multiple times in log statements. */
        String serverString = "[" + curServerSocket.getInetAddress().getHostAddress() + ":"
                + curServerSocket.getLocalPort() + "]";

        /* Keep running while the server socket is open. */
        while (!curServerSocket.isClosed() && hasNoError) {

            /* Try to accept a connection */
            Socket curClientSocket = null;
            try {
                logger.debug(serverString + " - Waiting for client...");
                curClientSocket = curServerSocket.accept();
                curClientSocket.setKeepAlive(true);
                //TODO Maybe we should do a disconnect 
            } catch (IOException e) {
                logger.debug(serverString + " - Server accept interrupted.");
                // Retry, because no Socket was created
                continue;
            }
            /* set the new Socket */
            this.hostCommunication.setClientSocket(curClientSocket);

            /* Check to see if a client successfully connected */
            if (curClientSocket != null) {
                final String connectionMessage = serverString + " - Client connected ("
                        + curClientSocket.getInetAddress().getHostAddress() + ":" + curClientSocket.getPort()
                        + ")";

                /* Log the connection */
                logger.info(connectionMessage);

                /* Call connect on the current communication. */
                this.hostCommunication.connect();

                /* Wait until the client socket is disconnected */
                synchronized (curClientSocket) {
                    while (!curClientSocket.isClosed() && curClientSocket.isConnected()) {
                        try {
                            /* Close the ServerSocket so that he couldn't accept 
                             * more than one connections a time (SYN/SYN ACK - Problem)
                             */
                            curServerSocket.close();
                            /* wait until the client connection is closed */
                            curClientSocket.wait();
                            /* bind the ServerSocket again, so that 
                             * new Connections can be made
                             */
                            PowerState powerState = this.hostCommunication.getPowerState();
                            logger.debug("Comm power state is " + powerState);
                            if (powerState != TCPServerOffCommunicationPowerState.getInstance()) {
                                hasNoError = bindServerSocket();
                            }
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            logger.debug("Interrupted Exception happened.");
                        }
                    }

                    /* Done waiting */

                }

            }

        } /* while (!serverSocket.isClosed())... */

        /* Server socket closed */

    } else {
        /* Log the error message. */
        logger.error(errorMessage);
        /* Force a shutdown of the component. */
        this.hostCommunication.turnOff();
    }
    /* All done running. */
}

From source file:Server.java

/**
 * This is the method that Listener objects call when they accept a
 * connection from a client. It either creates a Connection object for the
 * connection and adds it to the list of current connections, or, if the
 * limit on connections has been reached, it closes the connection.
 *///from w w w  .ja  v  a2s.co  m
protected synchronized void addConnection(Socket s, Service service) {
    // If the connection limit has been reached
    if (connections.size() >= maxConnections) {
        try {
            // Then tell the client it is being rejected.
            PrintWriter out = new PrintWriter(s.getOutputStream());
            out.print("Connection refused; " + "the server is busy; please try again later.\n");
            out.flush();
            // And close the connection to the rejected client.
            s.close();
            // And log it, of course
            log("Connection refused to " + s.getInetAddress().getHostAddress() + ":" + s.getPort()
                    + ": max connections reached.");
        } catch (IOException e) {
            log(e);
        }
    } else { // Otherwise, if the limit has not been reached
        // Create a Connection thread to handle this connection
        Connection c = new Connection(s, service);
        // Add it to the list of current connections
        connections.add(c);
        // Log this new connection
        log("Connected to " + s.getInetAddress().getHostAddress() + ":" + s.getPort() + " on port "
                + s.getLocalPort() + " for service " + service.getClass().getName());
        // And start the Connection thread to provide the service
        c.start();
    }
}

From source file:org.jivesoftware.smack.XMPPConnection.java

/**
 * The server has indicated that TLS negotiation can start. We now need to secure the
 * existing plain connection and perform a handshake. This method won't return until the
 * connection has finished the handshake or an error occured while securing the connection.
 *
 * @throws Exception if an exception occurs.
 *///w  w w . j a v  a  2  s .c  o  m
void proceedTLSReceived() throws Exception {
    SSLContext context = SSLContext.getInstance("TLS");
    KeyStore ks = null;
    KeyManager[] kms = null;
    PasswordCallback pcb = null;

    if (config.getCallbackHandler() == null) {
        ks = null;
    } else {
        //System.out.println("Keystore type: "+configuration.getKeystoreType());
        if (config.getKeystoreType().equals("NONE")) {
            ks = null;
            pcb = null;
        } else if (config.getKeystoreType().equals("PKCS11")) {
            try {
                Constructor c = Class.forName("sun.security.pkcs11.SunPKCS11")
                        .getConstructor(InputStream.class);
                String pkcs11Config = "name = SmartCard\nlibrary = " + config.getPKCS11Library();
                ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes());
                Provider p = (Provider) c.newInstance(config);
                Security.addProvider(p);
                ks = KeyStore.getInstance("PKCS11", p);
                pcb = new PasswordCallback("PKCS11 Password: ", false);
                this.config.getCallbackHandler().handle(new Callback[] { pcb });
                ks.load(null, pcb.getPassword());
            } catch (Exception e) {
                ks = null;
                pcb = null;
            }
        } else if (config.getKeystoreType().equals("Apple")) {
            ks = KeyStore.getInstance("KeychainStore", "Apple");
            ks.load(null, null);
            //pcb = new PasswordCallback("Apple Keychain",false);
            //pcb.setPassword(null);
        } else {
            ks = KeyStore.getInstance(config.getKeystoreType());
            try {
                pcb = new PasswordCallback("Keystore Password: ", false);
                config.getCallbackHandler().handle(new Callback[] { pcb });
                ks.load(new FileInputStream(config.getKeystorePath()), pcb.getPassword());
            } catch (Exception e) {
                ks = null;
                pcb = null;
            }
        }
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        try {
            if (pcb == null) {
                kmf.init(ks, null);
            } else {
                kmf.init(ks, pcb.getPassword());
                pcb.clearPassword();
            }
            kms = kmf.getKeyManagers();
        } catch (NullPointerException npe) {
            kms = null;
        }
    }

    // Verify certificate presented by the server
    context.init(kms, new javax.net.ssl.TrustManager[] { new ServerTrustManager(getServiceName(), config) },
            new java.security.SecureRandom());
    Socket plain = socket;
    // Secure the plain connection
    socket = context.getSocketFactory().createSocket(plain, plain.getInetAddress().getHostName(),
            plain.getPort(), true);
    socket.setSoTimeout(0);
    socket.setKeepAlive(true);
    // Initialize the reader and writer with the new secured version
    initReaderAndWriter();
    // Proceed to do the handshake
    ((SSLSocket) socket).startHandshake();
    //if (((SSLSocket) socket).getWantClientAuth()) {
    //    System.err.println("Connection wants client auth");
    //}
    //else if (((SSLSocket) socket).getNeedClientAuth()) {
    //    System.err.println("Connection needs client auth");
    //}
    //else {
    //    System.err.println("Connection does not require client auth");
    // }
    // Set that TLS was successful
    usingTLS = true;

    // Set the new  writer to use
    packetWriter.setWriter(writer);
    // Send a new opening stream to the server
    packetWriter.openStream();
}

From source file:com.grendelscan.proxy.ssl.TunneledSSLConnection.java

public TunneledSSLConnection(Socket socket, String destinationHostname)
        throws SSLException, IOException, GeneralSecurityException {
    LOGGER.trace("Instantiating TunneledSSLConnection");
    this.destinationHostname = destinationHostname;
    this.socket = socket;
    if (socket == null) {
        IllegalArgumentException e = new IllegalArgumentException("socket cannot be null");
        LOGGER.error("Socket cannot be null", e);
        throw e;/*from  ww  w.j  ava 2  s .co  m*/
    }

    if (destinationHostname == null) {
        IllegalArgumentException e = new IllegalArgumentException("destinationHostname cannot be null");
        LOGGER.error("destinationHostname cannot be null", e);
        throw e;
    }

    SSLSocketFactory sslSocketFactory = initializeSSLFactory();
    HttpParams params = MiscHttpFactory.createDefaultHttpProxyParams();

    int buffersize = HttpConnectionParams.getSocketBufferSize(params);
    sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, socket.getInetAddress().getHostAddress(),
            socket.getPort(), true);
    sslSocket.setUseClientMode(false);

    sslInputStream = sslSocket.getInputStream();
    sslTunnelInputBuffer = new SSLTunnelInputBuffer(sslInputStream, buffersize, params);

    sslOutputStream = sslSocket.getOutputStream();
    sslTunnelOutputBuffer = new SSLTunnelOutputBuffer(sslOutputStream, buffersize, params);

    // This is the real important part where we identify the buffers to the parent
    init(sslTunnelInputBuffer, sslTunnelOutputBuffer, params);
    open = true;
}

From source file:com.isecpartners.gizmo.HttpRequest.java

private SSLSocket negotiateSSL(Socket sock, String hostname) throws KeyManagementException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, IOException,
        InvalidKeyException, SignatureException, NoSuchProviderException, NoCertException {
    synchronized (_factories) {
        SSLSocketFactory factory = _factories.get(hostname);

        if (factory == null) {
            factory = initSSL(hostname);
        }/*from w w w  .  j a v a2  s.  c  o m*/
        String inbound_hostname = sock.getInetAddress().getHostName();
        int inbound_port = sock.getPort();
        SSLSocket sslsock = (SSLSocket) factory.createSocket(sock, inbound_hostname, inbound_port, true);
        sslsock.setUseClientMode(false);
        if (!sslsock.isConnected()) {
            Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, "Couldn't negotiate SSL");
            System.exit(-1);
        }
        return sslsock;
    }
}

From source file:com.buaa.cfs.utils.NetUtils.java

/**
 * Like {@link NetUtils#connect(Socket, SocketAddress, int)} but also takes a local address and port to bind the
 * socket to./*w w w  .j  a v  a  2  s  .  c o  m*/
 *
 * @param socket
 * @param endpoint  the remote address
 * @param localAddr the local address to bind the socket to
 * @param timeout   timeout in milliseconds
 */
public static void connect(Socket socket, SocketAddress endpoint, SocketAddress localAddr, int timeout)
        throws IOException {
    if (socket == null || endpoint == null || timeout < 0) {
        throw new IllegalArgumentException("Illegal argument for connect()");
    }

    SocketChannel ch = socket.getChannel();

    if (localAddr != null) {
        Class localClass = localAddr.getClass();
        Class remoteClass = endpoint.getClass();
        Preconditions.checkArgument(localClass.equals(remoteClass),
                "Local address %s must be of same family as remote address %s.", localAddr, endpoint);
        socket.bind(localAddr);
    }

    try {
        if (ch == null) {
            // let the default implementation handle it.
            socket.connect(endpoint, timeout);
        } else {
            //        SocketIOWithTimeout.connect(ch, endpoint, timeout);
        }
    } catch (SocketTimeoutException ste) {
        //      throw new ConnectTimeoutException(ste.getMessage());
    }

    // There is a very rare case allowed by the TCP specification, such that
    // if we are trying to connect to an endpoint on the local machine,
    // and we end up choosing an ephemeral port equal to the destination port,
    // we will actually end up getting connected to ourself (ie any data we
    // send just comes right back). This is only possible if the target
    // daemon is down, so we'll treat it like connection refused.
    if (socket.getLocalPort() == socket.getPort() && socket.getLocalAddress().equals(socket.getInetAddress())) {
        LOG.info("Detected a loopback TCP socket, disconnecting it");
        socket.close();
        throw new ConnectException("Localhost targeted connection resulted in a loopback. "
                + "No daemon is listening on the target port.");
    }
}

From source file:com.stratuscom.harvester.codebase.ClassServer.java

private boolean processRequest(Socket sock) {
    try {// w  w  w .  j  av a2  s  . c  o  m
        DataOutputStream out = new DataOutputStream(sock.getOutputStream());
        String req;
        try {
            req = getInput(sock, true);
        } catch (Exception e) {
            logger.log(Level.FINE, "reading request", e);
            return true;
        }
        if (req == null) {
            return true;
        }
        String[] args = new String[3];
        boolean get = req.startsWith("GET ");
        if (!get && !req.startsWith("HEAD ")) {
            processBadRequest(args, out);
        }
        String path = parsePathFromRequest(req, get);
        if (path == null) {
            return processBadRequest(args, out);
        }
        if (args != null) {
            args[0] = path;
        }
        args[1] = sock.getInetAddress().getHostName();
        args[2] = Integer.toString(sock.getPort());

        logger.log(Level.FINER,
                get ? MessageNames.CLASS_SERVER_RECEIVED_REQUEST : MessageNames.CLASS_SERVER_RECEIVED_PROBE,
                args);
        byte[] bytes;
        try {
            bytes = getBytes(path);
        } catch (Exception e) {
            logger.log(Level.WARNING, MessageNames.CLASS_SERVER_EXCEPTION_GETTING_BYTES, e);
            out.writeBytes("HTTP/1.0 500 Internal Error\r\n\r\n");
            out.flush();
            return true;
        }
        if (bytes == null) {
            logger.log(Level.FINE, MessageNames.CLASS_SERVER_NO_CONTENT_FOUND, path);
            out.writeBytes("HTTP/1.0 404 Not Found\r\n\r\n");
            out.flush();
            return true;
        }
        writeHeader(out, bytes);
        if (get) {
            out.write(bytes);
        }
        out.flush();
        return false;
    } catch (Exception e) {
        logger.log(Level.FINE, MessageNames.CLASS_SERVER_EXCEPTION_WRITING_RESPONSE, e);
    } finally {
        try {
            sock.close();
        } catch (IOException e) {
        }
    }
    return false;
}

From source file:org.eclipse.jubula.communication.Communicator.java

/**
 * Initializes the given connection and socket, adding necessary listeners
 * and starting to read the input stream of the socket.
 * /*from  w w  w . j a v  a2  s  .c  o m*/
 * @param conn The connection to initialize.
 * @param socket The socket associated with the connection.
 */
private void setup(Connection conn, Socket socket) {
    // add listener
    conn.addMessageHandler(m_connectionListener);
    conn.addErrorHandler(m_errorListener);
    // set an exceptionHandler
    conn.setExceptionHandler(getExceptionHandler());
    // start reading from connection
    String id = socket.toString();
    conn.startReading(id);
    fireConnectionGained(socket.getInetAddress(), socket.getPort());
}

From source file:ch.cyberduck.core.ftp.FTPClient.java

@Override
protected void _prepareDataSocket_(final Socket socket) throws IOException {
    if (preferences.getBoolean("ftp.tls.session.requirereuse")) {
        if (socket instanceof SSLSocket) {
            // Control socket is SSL
            final SSLSession session = ((SSLSocket) _socket_).getSession();
            if (session.isValid()) {
                final SSLSessionContext context = session.getSessionContext();
                context.setSessionCacheSize(preferences.getInteger("ftp.ssl.session.cache.size"));
                try {
                    final Field sessionHostPortCache = context.getClass()
                            .getDeclaredField("sessionHostPortCache");
                    sessionHostPortCache.setAccessible(true);
                    final Object cache = sessionHostPortCache.get(context);
                    final Method method = cache.getClass().getDeclaredMethod("put", Object.class, Object.class);
                    method.setAccessible(true);
                    method.invoke(cache, String.format("%s:%s", socket.getInetAddress().getHostName(),
                            String.valueOf(socket.getPort())).toLowerCase(Locale.ROOT), session);
                    method.invoke(cache, String.format("%s:%s", socket.getInetAddress().getHostAddress(),
                            String.valueOf(socket.getPort())).toLowerCase(Locale.ROOT), session);
                } catch (NoSuchFieldException e) {
                    // Not running in expected JRE
                    log.warn("No field sessionHostPortCache in SSLSessionContext", e);
                } catch (Exception e) {
                    // Not running in expected JRE
                    log.warn(e.getMessage());
                }/*from w  w  w  .  j ava 2 s  . com*/
            } else {
                log.warn(String.format("SSL session %s for socket %s is not rejoinable", session, socket));
            }
        }
    }
}