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:it.anyplace.sync.core.security.KeystoreHandler.java

public Socket wrapSocket(Socket socket, boolean isServerSocket, final String... protocols)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException,
        IOException {//from  ww w  . j av  a  2s  . c om
    logger.debug("wrapping plain socket, server mode = {}", isServerSocket);
    SSLSocket sslSocket = (SSLSocket) getSocketFactory().createSocket(socket, null, socket.getPort(), true);
    if (isServerSocket) {
        sslSocket.setUseClientMode(false);
    }
    enableALPN(sslSocket, protocols);
    return sslSocket;
}

From source file:gov.hhs.fha.nhinc.lift.clientController.SocketClientManagerController.java

@Override
public final void run() {

    while (true) {
        Socket socket = null;
        InputStream in = null;/* w ww  .j  a  v  a  2s  . co  m*/
        URI writtenFile = null;
        String errorMesg = null;
        LiftMessage mesg = null;
        try {

            socket = server.accept();
            while (socket == null) {
                socket = server.accept();
            }
            in = socket.getInputStream();
            log.debug("Server " + server.getInetAddress() + " connecting to socket " + socket.getInetAddress()
                    + ": " + socket.getPort());

            InterProcessSocketProtocol processSocket = new InterProcessSocketProtocol();
            String message = processSocket.readData(in);
            log.info("SocketClientManagerController received message: " + message);
            if (message != null) {
                mesg = (LiftMessage) JaxbUtil.unmarshalFromReader(new StringReader(message), LiftMessage.class);
                System.out.println("Setting " + mesg.getRequest().getRequest() + " to in progress");
                mesgState.add(mesg.getRequest().getRequest());
                writtenFile = manager.startClient(mesg, this);
            }
        } catch (JAXBException ex) {
            errorMesg = "Client is unable to process LiftMessage " + ex.getMessage();
            log.error(errorMesg);
        } catch (IOException e) {
            errorMesg = "Client is unable to process incoming socket information " + e.getMessage();
            log.error(errorMesg);
        } finally {
            if (socket != null) {
                try {
                    log.debug("Closing socket " + socket);
                    socket.close();
                } catch (IOException ex) {
                    log.warn("Unable to close socket " + socket);
                }
            }

            if (writtenFile != null) {
                reportSuccess(mesg.getRequest().getRequest(), writtenFile);
            } else {
                if (mesg != null && mesg.getRequest() != null && mesg.getRequest().getRequest() != null) {
                    reportFailure(mesg.getRequest().getRequest(), errorMesg);
                } else {
                    reportFailure(null, errorMesg);
                }

            }

        }
    }
}

From source file:org.parosproxy.paros.network.SSLConnector.java

/**
 * Create a SSLsocket using an existing connected socket. It can be used
 * such as a tunneled SSL proxy socket (eg when a CONNECT request is
 * received). This SSLSocket will start server side handshake immediately.
 * /*from  w  w w. j  a va 2 s .c o m*/
 * @param targethost the host where you want to connect to 
 * @param socket
 * @return
 * @throws IOException
 */
public Socket createTunnelServerSocket(String targethost, Socket socket) throws IOException {
    // ZAP: added host name parameter
    SSLSocket s = (SSLSocket) getTunnelSSLSocketFactory(targethost).createSocket(socket,
            socket.getInetAddress().getHostAddress(), socket.getPort(), true);

    s.setUseClientMode(false);
    s.startHandshake();
    return s;
}

From source file:org.springframework.integration.ip.tcp.connection.TcpConnectionSupport.java

/**
 * Creates a {@link TcpConnectionSupport} object and publishes a
 * {@link TcpConnectionOpenEvent}, if an event publisher is provided.
 * @param socket the underlying socket.//  w w w  .  j  ava2 s. c  o  m
 * @param server true if this connection is a server connection
 * @param lookupHost true if reverse lookup of the host name should be performed,
 * otherwise, the ip address will be used for identification purposes.
 * @param applicationEventPublisher the publisher to which open, close and exception events will
 * be sent; may be null if event publishing is not required.
 * @param connectionFactoryName the name of the connection factory creating this connection; used
 * during event publishing, may be null, in which case "unknown" will be used.
 */
public TcpConnectionSupport(Socket socket, boolean server, boolean lookupHost,
        ApplicationEventPublisher applicationEventPublisher, String connectionFactoryName) {
    this.server = server;
    InetAddress inetAddress = socket.getInetAddress();
    if (inetAddress != null) {
        this.hostAddress = inetAddress.getHostAddress();
        if (lookupHost) {
            this.hostName = inetAddress.getHostName();
        } else {
            this.hostName = this.hostAddress;
        }
    }
    int port = socket.getPort();
    this.connectionId = this.hostName + ":" + port + ":" + UUID.randomUUID().toString();
    try {
        this.soLinger = socket.getSoLinger();
    } catch (SocketException e) {
    }
    this.applicationEventPublisher = applicationEventPublisher;
    if (connectionFactoryName != null) {
        this.connectionFactoryName = connectionFactoryName;
    }
    this.publishConnectionOpenEvent();
    if (logger.isDebugEnabled()) {
        logger.debug("New connection " + this.getConnectionId());
    }
}

From source file:org.apache.jmeter.protocol.amf.proxy.AmfProxy.java

/**
 * Negotiate a SSL connection.//  w  w w.  ja  va  2 s.c o  m
 *
 * @param sock socket in
 * @param host
 * @return a new client socket over ssl
 * @throws Exception if negotiation failed
 */
private Socket startSSL(Socket sock, String host) throws IOException {
    SSLSocketFactory sslFactory = getSSLSocketFactory(host);
    SSLSocket secureSocket;
    if (sslFactory != null) {
        try {
            secureSocket = (SSLSocket) sslFactory.createSocket(sock, sock.getInetAddress().getHostName(),
                    sock.getPort(), true);
            secureSocket.setUseClientMode(false);
            if (log.isDebugEnabled()) {
                log.debug("SSL transaction ok with cipher: " + secureSocket.getSession().getCipherSuite());
            }
            return secureSocket;
        } catch (IOException e) {
            log.error("Error in SSL socket negotiation: ", e);
            throw e;
        }
    } else {
        log.warn("Unable to negotiate SSL transaction, no keystore?");
        throw new IOException("Unable to negotiate SSL transaction, no keystore?");
    }
}

From source file:gov.hhs.fha.nhinc.lift.proxy.properties.imp.ProducerProxyPropertiesService.java

@Override
public Socket getSocketToServerForRequest(LiftConnectionRequestToken request) throws IOException {

    Socket socket = new Socket();
    try {/*  w w w  .j a va  2 s . c  o  m*/
        String fileServerIP = PropertyAccessor.getProperty(NhincConstants.GATEWAY_PROPERTY_FILE,
                NhincConstants.LIFT_FILESERVER_IP);
        String fileServerPort = PropertyAccessor.getProperty(NhincConstants.GATEWAY_PROPERTY_FILE,
                NhincConstants.LIFT_FILESERVER_PORT);
        int portNum = Integer.parseInt(fileServerPort);

        SocketAddress socketAddr = new InetSocketAddress(fileServerIP, portNum);
        socket.connect(socketAddr);

    } catch (PropertyAccessException ex) {
        log.error(ex.getMessage());
    }
    log.debug("Creating socket " + socket.getInetAddress() + ": " + socket.getPort());
    return socket;
}

From source file:Proxy.java

String toString(SocketChannel ch) {
    StringBuilder sb = new StringBuilder();
    Socket sock;

    if (ch == null)
        return null;
    if ((sock = ch.socket()) == null)
        return null;
    sb.append(sock.getInetAddress().getHostName()).append(':').append(sock.getPort());
    return sb.toString();
}

From source file:org.beepcore.beep.profile.tls.jsse.TLSProfileJSSE.java

public void receiveMSG(MessageMSG msg) {
    Channel channel = msg.getChannel();

    InputDataStreamAdapter is = msg.getDataStream().getInputStream();

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));

    String data;//from w w w  . j  a  v a 2 s.  c  om

    try {
        try {
            data = reader.readLine();
        } catch (IOException e) {
            msg.sendERR(BEEPError.CODE_PARAMETER_ERROR, "Error reading data");
            return;
        }

        if (data.equals(READY1) == false && data.equals(READY2) == false) {
            msg.sendERR(BEEPError.CODE_PARAMETER_INVALID, "Expected READY element");
        }

        this.begin(channel);

        msg.sendRPY(new StringOutputDataStream(PROCEED2));
    } catch (BEEPException e1) {
        channel.getSession().terminate("unable to send ERR");
        return;
    }

    try {
        Socket oldSocket = ((TCPSession) channel.getSession()).getSocket();
        /** @TODO add support for serverName */
        SSLSocket newSocket = (SSLSocket) socketFactory.createSocket(oldSocket,
                oldSocket.getInetAddress().getHostName(), oldSocket.getPort(), true);

        BeepListenerHCL l = new BeepListenerHCL(channel);

        newSocket.addHandshakeCompletedListener(l);
        newSocket.setUseClientMode(false);
        newSocket.setNeedClientAuth(needClientAuth);
        newSocket.setEnabledCipherSuites(newSocket.getSupportedCipherSuites());
        if (sslProtocols != null) {
            newSocket.setEnabledProtocols(sslProtocols);
        }

        newSocket.startHandshake();
    } catch (IOException e) {
        channel.getSession().terminate("TLS error: " + e.getMessage());
        return;
    }
}

From source file:com.linuxbox.enkive.mailprocessor.AbstractMailProcessor.java

@Override
public void initializeProcessor(AbstractSocketServer server, Socket socket) {
    if (LOGGER.isTraceEnabled())
        LOGGER.trace("in initializeProcessor");
    this.server = server;
    this.socket = socket;

    closeInitiated = false;/* w  w  w .java 2  s .c  o m*/

    // set the socket linger options, so the socket closes immediately when
    // closed
    try {
        socket.setSoLinger(false, 0);
    } catch (SocketException e) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("enkive session unable to set socket linger " + e);
    }

    if (isJmxEnabled()) {
        String type = getClass().getSimpleName();
        String name = "Port " + socket.getPort();

        mBeanName = MBeanUtils.registerMBean(this, type, name);
        if (LOGGER.isTraceEnabled())
            LOGGER.trace("registered mbean " + mBeanName + " (" + type + "/" + name + ")");
    }

    initialized = true;
}

From source file:org.beepcore.beep.profile.tls.jsse.TLSProfileJSSE.java

/**
 * start a channel for the TLS profile.  Besides issuing the
 * channel start request, it also performs the initiator side
 * chores necessary to begin encrypted communication using TLS
 * over a session.  Parameters regarding the type of encryption
 * and whether or not authentication is required are specified
 * using the profile configuration passed to the <code>init</code>
 * method Upon returning, all traffic over the session will be
 * entrusted as per these parameters.<p>
 *
 * @see #init init - profile configuration
 * @param session The session to encrypt communcation for
 *
 * @return new <code>Session</code> with TLS negotiated.
 * @throws BEEPException an error occurs during the channel start
 * request or the TLS handshake (such as trying to negotiate an
 * anonymous connection with a peer that doesn't support an
 * anonymous cipher suite)./*from   w  ww. j ava  2 s . c o  m*/
 */
public TCPSession startTLS(TCPSession session) throws BEEPException {
    Channel ch = startChannel(session, uri, false, READY2, null);

    // See if we got start data back
    String data = ch.getStartData();

    if (log.isDebugEnabled()) {
        log.debug("Got start data of " + data);
    }

    // Consider the data (see if it's proceed)
    if ((data == null) || (!data.equals(PROCEED1) && !data.equals(PROCEED2))) {
        log.error("Invalid reply: " + data);
        throw new BEEPException(ERR_EXPECTED_PROCEED);
    }

    // Freeze IO and get the socket and reset it to TLS
    Socket oldSocket = session.getSocket();
    SSLSocket newSocket = null;
    TLSHandshake l = new TLSHandshake();

    // create the SSL Socket
    try {
        newSocket = (SSLSocket) socketFactory.createSocket(oldSocket, oldSocket.getInetAddress().getHostName(),
                oldSocket.getPort(), true);

        newSocket.addHandshakeCompletedListener(l);
        newSocket.setUseClientMode(true);
        newSocket.setNeedClientAuth(needClientAuth);
        newSocket.setEnabledCipherSuites(newSocket.getSupportedCipherSuites());
        if (this.sslProtocols != null) {
            newSocket.setEnabledProtocols(sslProtocols);
        }

        // set up so the handshake listeners will be called
        l.session = session;

        log.debug("Handshake starting");
        newSocket.startHandshake();
        log.debug("Handshake returned");

        synchronized (l) {
            if (!l.notifiedHandshake) {
                l.waitingForHandshake = true;

                l.wait();

                l.waitingForHandshake = false;
            }
        }
        log.debug("Handshake done waiting");
    } catch (javax.net.ssl.SSLException e) {
        log.error(e);
        throw new BEEPException(e);
    } catch (java.io.IOException e) {
        log.error(e);
        throw new BEEPException(ERR_TLS_SOCKET);
    } catch (InterruptedException e) {
        log.error(e);
        throw new BEEPException(ERR_TLS_HANDSHAKE_WAIT);
    }

    // swap it out for the new one with TLS enabled.
    if (abortSession) {
        session.close();

        throw new BEEPException(ERR_TLS_NO_AUTHENTICATION);
    } else {
        Hashtable hash = new Hashtable();

        hash.put(SessionTuningProperties.ENCRYPTION, "true");

        SessionTuningProperties tuning = new SessionTuningProperties(hash);

        return (TCPSession) reset(session, generateCredential(), l.cred, tuning, session.getProfileRegistry(),
                newSocket);
    }
}