Example usage for java.net Socket getInetAddress

List of usage examples for java.net Socket getInetAddress

Introduction

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

Prototype

public InetAddress getInetAddress() 

Source Link

Document

Returns the address to which the socket is connected.

Usage

From source file:com.sshtools.daemon.SshServer.java

/**
 *
 *
 * @param socket/* w  ww . j a  va2  s  .c  o  m*/
 *
 * @return
 *
 * @throws IOException
 */
protected TransportProtocolServer createSession(Socket socket) throws IOException {
    log.debug("Initializing connection");

    InetAddress address = socket.getInetAddress();
    /*( (InetSocketAddress) socket
         .getRemoteSocketAddress()).getAddress();*/

    log.debug("Remote Hostname: " + address.getHostName());
    log.debug("Remote IP: " + address.getHostAddress());

    TransportProtocolServer transport = new TransportProtocolServer();

    // Create the Authentication Protocol
    AuthenticationProtocolServer authentication = new AuthenticationProtocolServer();

    // Create the Connection Protocol
    ConnectionProtocol connection = new ConnectionProtocol();

    // Configure the connections services
    configureServices(connection);

    // Allow the Connection Protocol to be accepted by the Authentication Protocol
    authentication.acceptService(connection);

    // Allow the Authentication Protocol to be accepted by the Transport Protocol
    transport.acceptService(authentication);

    transport.startTransportProtocol(new ConnectedSocketTransportProvider(socket),
            new SshConnectionProperties());

    return transport;
}

From source file:com.mindprotectionkit.freephone.signaling.SignalingSocket.java

private Socket timeoutHackConnect(SSLSocketFactory sslSocketFactory, String host, int port) throws IOException {
    InetAddress[] addresses = InetAddress.getAllByName(host);
    Socket stagedSocket = LowLatencySocketConnector.connect(addresses, port);

    Log.w("SignalingSocket", "Connected to: " + stagedSocket.getInetAddress().getHostAddress());

    SocketConnectMonitor monitor = new SocketConnectMonitor(stagedSocket);

    monitor.start();/*from   w w w  . jav  a2s.  c  o  m*/

    Socket result = sslSocketFactory.createSocket(stagedSocket, host, port, true);

    synchronized (this) {
        this.connectionAttemptComplete = true;
        notify();

        if (result.isConnected())
            return result;
        else
            throw new IOException("Socket timed out before " + "connection completed.");
    }
}

From source file:com.bittorrent.mpetazzoni.client.ConnectionHandler.java

/**
 * Return a human-readable representation of a connected socket channel.
 *
 * @param channel The socket channel to represent.
 * @return A textual representation (<em>host:port</em>) of the given
 * socket.//  w ww .j a  va2 s  . c om
 */
private String socketRepr(SocketChannel channel) {
    Socket s = channel.socket();
    return String.format("%s:%d%s", s.getInetAddress().getHostName(), s.getPort(),
            channel.isConnected() ? "+" : "-");
}

From source file:net.lightbody.bmp.proxy.jetty.http.ajp.AJP13Listener.java

/**
 * Handle Job. Implementation of ThreadPool.handle(), calls
 * handleConnection.//ww  w  .  j  a va  2s  .  c  o  m
 * 
 * @param socket
 *            A Connection.
 */
public void handleConnection(Socket socket) throws IOException {
    // Check acceptable remote servers
    if (_remoteServers != null && _remoteServers.length > 0) {
        boolean match = false;
        InetAddress inetAddress = socket.getInetAddress();
        String hostAddr = inetAddress.getHostAddress();
        String hostName = inetAddress.getHostName();
        for (int i = 0; i < _remoteServers.length; i++) {
            if (hostName.equals(_remoteServers[i]) || hostAddr.equals(_remoteServers[i])) {
                match = true;
                break;
            }
        }
        if (!match) {
            log.warn("AJP13 Connection from un-approved host: " + inetAddress);
            return;
        }
    }

    // Handle the connection
    socket.setTcpNoDelay(true);
    socket.setSoTimeout(getMaxIdleTimeMs());
    AJP13Connection connection = createConnection(socket);
    try {
        connection.handle();
    } finally {
        connection.destroy();
    }
}

From source file:edu.vt.middleware.gator.log4j.SocketServer.java

/** {@inheritDoc}. */
public synchronized void socketClosed(final Object sender, final Socket socket) {
    logger.info("Got notification of closed socket " + socket);

    final InetAddress addr = socket.getInetAddress();
    if (eventHandlerMap.containsKey(addr)) {
        logger.info(String.format("Cleaning up resources held by %s due to socket close.", addr));
        eventHandlerMap.get(addr).shutdown();
        eventHandlerMap.remove(addr);/*w  w  w . j a v  a 2  s . co  m*/
    }
}

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./*from  w w w . j ava  2  s .  com*/
 * @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.ftpserver.ssl.Ssl.java

/**
 * Returns a socket layered over an existing socket.
 *//*from  w w  w.j  av a  2  s.  co  m*/
public Socket createSocket(String protocol, Socket soc, boolean clientMode) throws Exception {

    // already wrapped - no need to do anything
    if (soc instanceof SSLSocket) {
        return soc;
    }

    // get socket factory
    SSLContext ctx = getSSLContext(protocol);
    SSLSocketFactory socFactory = ctx.getSocketFactory();

    // create socket
    String host = soc.getInetAddress().getHostAddress();
    int port = soc.getLocalPort();
    SSLSocket ssoc = (SSLSocket) socFactory.createSocket(soc, host, port, true);
    ssoc.setUseClientMode(clientMode);

    // initialize socket
    String cipherSuites[] = ssoc.getSupportedCipherSuites();
    ssoc.setEnabledCipherSuites(cipherSuites);
    ssoc.setNeedClientAuth(m_clientAuthReqd);

    return ssoc;
}

From source file:josejamilena.pfc.servidor.chartserver.ClientHandler.java

/**
 * Hilo de ejecucin del navegado cliente. Genera un pgina web para el
 * explorador cliente segn los datos disponibles.
 * @param s socket/* w w  w.j a  v a  2 s  . c o m*/
 */
public ClientHandler(final Socket s) {
    try {
        nombreFichero = RandomStringUtils.randomAlphabetic(longitudNombre);
        nombreFichero = nombreFichero + ".html";
        logger.info("Conexion desde: " + s.getInetAddress().toString());
        logger.info("Fichero index creado: " + nombreFichero);
        miSocketServidor = s;
        PrintWriter pw;
        Grafico g = null;
        Connection conn = DriverManager.getConnection(
                Webserver.getConfigProperties().getProperty("josejamilena.pfc.servidor.chartserver.url"));
        List<GrupoConsulta> lgc = SQLUtils.listaGruposConsultas(conn);
        List<String> googleCharts = new LinkedList<String>();
        if (lgc.size() == numGrupos) {
            GrupoConsulta gcHostSgbd = lgc.get(0);
            GrupoConsulta gcHostClientes = lgc.get(1);
            GrupoConsulta gcHostTipo = lgc.get(2);
            String plantilla1 = "";
            for (String tmp : gcHostSgbd.getLista()) {
                g = SQLUtils.consultaSQL2Grafico(conn, tmp);
                String textoAlternativo1 = "dibujo";
                String datos1 = "";
                for (String i : g.getLista()) {
                    datos1 = datos1 + "," + i;
                }
                String media1 = "";
                int cantidad = g.getLista().size();
                double mediad = 0.0;
                for (String i : g.getLista()) {
                    mediad = mediad + Double.parseDouble(i);
                }
                mediad = mediad / cantidad;
                for (String i : g.getLista()) {
                    media1 = media1 + "," + Math.round(mediad);
                }
                String leyendaDatos1 = tmp.substring(tmp.indexOf("'") + 1, tmp.lastIndexOf("'"));
                String tituloGrafico1 = "Servidor de bases de datos " + leyendaDatos1;
                String leyendaMedia1 = "media";
                String graficaActual = "<img src=\"http://chart.apis." + "google.com/chart?chs=600x400&chd=t:"
                        + datos1 + "|" + media1 + "&cht=lc&chtt=" + tituloGrafico1 + "&chts=FF0000,20&chdl="
                        + leyendaDatos1 + "|" + leyendaMedia1 + "&chco=ff0000,0000ff&chxt=y"
                        + "&chxl=1:|0|10000&chds=10,30000\"" + "  alt=\"" + textoAlternativo1 + "\">";
                graficaActual = graficaActual.replace("chd=t:,", "chd=t:");
                graficaActual = graficaActual.replace("|,", "|");
                plantilla1 = plantilla1 + "<p>" + graficaActual;
            }
            googleCharts.add(plantilla1);
            String plantilla2 = "";
            for (String tmp : gcHostClientes.getLista()) {
                g = SQLUtils.consultaSQL2Grafico(conn, tmp);
                String textoAlternativo2 = "dibujo";
                String datos2 = "";
                for (String i : g.getLista()) {
                    datos2 = datos2 + "," + i;
                }
                String media2 = "";
                int cantidad = g.getLista().size();
                double mediad = 0.0;
                for (String i : g.getLista()) {
                    mediad = mediad + Double.parseDouble(i);
                }
                mediad = mediad / cantidad;
                for (String i : g.getLista()) {
                    media2 = media2 + "," + Math.round(mediad);
                }
                String leyendaDatos2 = tmp.substring(tmp.indexOf("'") + 1, tmp.lastIndexOf("'"));
                String tituloGrafico2 = "Cliente de bases de datos " + leyendaDatos2;
                String leyendaMedia2 = "media";
                String graficaActual = "<img src=\"http://chart.apis." + "google.com/chart?chs=600x400&chd=t:"
                        + datos2 + "|" + media2 + "&cht=lc&chtt=" + tituloGrafico2 + "&chts=FF0000,20&chdl="
                        + leyendaDatos2 + "|" + leyendaMedia2 + "&chco=00FF00,0000ff&chxt=y"
                        + "&chxl=1:|0|10000&chds=10,30000\"" + "  alt=\"" + textoAlternativo2 + "\">";
                graficaActual = graficaActual.replace("chd=t:,", "chd=t:");
                graficaActual = graficaActual.replace("|,", "|");
                plantilla2 = plantilla2 + "<p>" + graficaActual;
            }
            googleCharts.add(plantilla2);
            String plantilla3 = "";
            for (String tmp : gcHostTipo.getLista()) {
                g = SQLUtils.consultaSQL2Grafico(conn, tmp);
                String textoAlternativo3 = "dibujo";
                String datos3 = "";
                for (String i : g.getLista()) {
                    datos3 = datos3 + "," + i;
                }
                String media3 = "";
                int cantidad = g.getLista().size();
                double mediad = 0.0;
                for (String i : g.getLista()) {
                    mediad = mediad + Double.parseDouble(i);
                }
                mediad = mediad / cantidad;
                for (String i : g.getLista()) {
                    media3 = media3 + "," + Math.round(mediad);
                }
                String leyendaDatos3 = tmp.substring(tmp.indexOf("'") + 1, tmp.lastIndexOf("'"));
                String tituloGrafico3 = "Script " + leyendaDatos3;
                String leyendaMedia3 = "media";
                String graficaActual = "<img src=\"http://chart.apis." + "google.com/chart?chs=600x400&chd=t:"
                        + datos3 + "|" + media3 + "&cht=lc&chtt=" + tituloGrafico3 + "&chts=FF0000,20&chdl="
                        + leyendaDatos3 + "|" + leyendaMedia3 + "&chco=000000,0000ff&chxt=y&"
                        + "chxl=1:|0|10000&chds=10,30000\"" + "  alt=\"" + textoAlternativo3 + "\">";
                graficaActual = graficaActual.replace("chd=t:,", "chd=t:");
                graficaActual = graficaActual.replace("|,", "|");
                plantilla3 = plantilla3 + "<p>" + graficaActual;
            }
            googleCharts.add(plantilla3);
        }
        String titulo = "Estadisticas online";
        String script = "<script type=\"text/JavaScript\">" + "<!-- function timedRefresh(timeoutPeriod) {"
                + "setTimeout(\"location.reload(true);\",timeoutPeriod);" + "} //   -->  </script> ";
        String encabezado = "<html><head><meta content=\"text/html; "
                + "charset=ISO-8859-1\" http-equiv=\"content-type\"><title>" + titulo + "</title>" + script
                + "</head> <body onload=\"JavaScript:timedRefresh(5000);\">" + " <h1>" + titulo
                + "</h1><br><br><br> ";
        String graficas = "";
        for (String i : googleCharts) {
            graficas = graficas + "<br><br><br>" + i;
        }
        String pie = "<br>Powered by: <A HREF=\"http://www.google.com/\">"
                + "<IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\" "
                + "border=\"0\" ALT=\"Google\" align=\"absmiddle\">" + "</A></body> </html>";
        pw = new PrintWriter(nombreFichero);
        pw.println(encabezado + graficas + pie);
        pw.flush();
        pw.close();
        start();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:lockstep.LockstepServer.java

/**
 * This method puts the server in waiting for client connections. It returns
 * when the expected number of clients have successfully completed the 
 * handshake./*  ww w.jav  a  2 s . c om*/
 * Parallel threads are started to handle the handshakes.
 * In case of failure, all threads are interrupted and then the exception is
 * propagated.
 * 
 * @throws IOException In case of failure on opening the ServerSocket and 
 * accepting connections through it 
 * @throws InterruptedException In case of failure during the handshake 
 * sessions
 */
private void handshakePhase() throws IOException, InterruptedException {
    ServerSocket tcpServerSocket = new ServerSocket(tcpPort);

    CyclicBarrier barrier = new CyclicBarrier(this.clientsNumber);
    CountDownLatch latch = new CountDownLatch(this.clientsNumber);

    //Each session of the protocol starts with a different random frame number
    int firstFrameNumber = (new Random()).nextInt(1000) + 100;

    Thread[] handshakeSessions = new Thread[clientsNumber];

    for (int i = 0; i < clientsNumber; i++) {
        Socket tcpConnectionSocket = tcpServerSocket.accept();
        LOG.info("Connection " + i + " accepted from " + tcpConnectionSocket.getInetAddress().getHostAddress());
        handshakeSessions[i] = new Thread(
                () -> serverHandshakeProtocol(tcpConnectionSocket, firstFrameNumber, barrier, latch, this));
        handshakeSessions[i].start();
    }
    try {
        latch.await();
    } catch (InterruptedException inEx) {
        for (Thread handshakeSession : handshakeSessions)
            handshakeSession.interrupt();

        for (Thread handshakeSession : handshakeSessions)
            handshakeSession.join();

        throw new InterruptedException();
    }
    LOG.info("All handshakes completed");
}

From source file:at.tugraz.ist.akm.webservice.server.ServerThread.java

@Override
public void run() {
    mRunning = true;//from  w ww  . j a v a2  s  . c  om
    while (mRunning) {
        Socket socket = null;
        try {
            socket = mServerSocket != null ? mServerSocket.accept() : null;
        } catch (IOException ioException) {
            // OK: no need to write trace
        }

        if (mStopServerThread) {
            break;
        }
        if (socket != null) {
            mLog.debug("connection request from ip <" + socket.getInetAddress() + "> on port <"
                    + socket.getPort() + ">");

            final Socket finalSocketReference = socket;
            try {
                mThreadPool.executeTask(new Runnable() {
                    @Override
                    public void run() {
                        DefaultHttpServerConnection serverConn = new DefaultHttpServerConnection();
                        try {
                            HttpParams params = new BasicHttpParams();
                            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
                            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

                            serverConn.bind(finalSocketReference, params);
                            HttpService httpService = initializeHTTPService();
                            httpService.handleRequest(serverConn, mHttpContext);

                            synchronized (ServerThread.this) {
                                HttpConnectionMetrics connMetrics = serverConn.getMetrics();
                                mSentBytesCount += connMetrics.getSentBytesCount();
                                mReceivedBytesCount += connMetrics.getReceivedBytesCount();
                            }
                        } catch (SSLException iDon_tCare) {
                            // some browser send connection closed, some
                            // not ...
                            mLog.info("ignore SSL-connection closed by peer");
                        } catch (ConnectionClosedException iDon_tCare) {
                            mLog.info("ignore connection closed by peer");
                        } catch (Exception ex) {
                            mLog.error("exception caught while processing HTTP client connection", ex);
                        }
                    }
                });
            } catch (RejectedExecutionException reason) {
                mLog.error("request execution rejected because pool works at its limit", reason);
            }
        }
    }

    mRunning = false;
    mLog.info("webserver stopped");
}