Example usage for java.net Socket getRemoteSocketAddress

List of usage examples for java.net Socket getRemoteSocketAddress

Introduction

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

Prototype

public SocketAddress getRemoteSocketAddress() 

Source Link

Document

Returns the address of the endpoint this socket is connected to, or null if it is unconnected.

Usage

From source file:org.apache.hadoop.hdfs.SocketCache.java

/**
 * Give an unused socket to the cache.//w ww.  java2s .  co m
 * @param sock socket not used by anyone.
 */
public synchronized void put(Socket sock, IOStreamPair ioStreams) {

    Preconditions.checkNotNull(sock);
    SocketAndStreams s = new SocketAndStreams(sock, ioStreams);
    if (capacity <= 0) {
        // Cache disabled.
        s.close();
        return;
    }

    startExpiryDaemon();

    SocketAddress remoteAddr = sock.getRemoteSocketAddress();
    if (remoteAddr == null) {
        LOG.warn("Cannot cache (unconnected) socket with no remote address: " + sock);
        IOUtils.closeSocket(sock);
        return;
    }

    if (capacity == multimap.size()) {
        evictOldest();
    }
    multimap.put(remoteAddr, s);
}

From source file:com.subgraph.vega.internal.http.proxy.HttpProxy.java

private void proxyAcceptLoop() {
    while (!Thread.interrupted()) {
        Socket s;
        try {//from www. j  a v  a 2  s .  co m
            s = serverSocket.accept();
        } catch (IOException e) {
            if (!Thread.interrupted()) {
                logger.log(Level.WARNING, "IO error processing incoming connection: " + e.getMessage(), e);
            }
            break;
        }

        logger.fine("Connection accepted from " + s.getRemoteSocketAddress());
        VegaHttpServerConnection c = new VegaHttpServerConnection(params);
        try {
            c.bind(s, params);
        } catch (IOException e) {
            logger.log(Level.WARNING, "Unexpected error: " + e.getMessage(), e);
            continue;
        }

        final ConnectionTask task = new ConnectionTask(httpService, c, HttpProxy.this);
        synchronized (connectionList) {
            connectionList.add(task);
        }
        executor.execute(task);
    }

    synchronized (connectionList) {
        for (ConnectionTask task : connectionList) {
            task.shutdown();
        }
    }

    executor.shutdownNow();
}

From source file:com.devoteam.srit.xmlloader.http.bio.BIOSocketServerListener.java

public void run() {
    try {//from w  w w  .  j  a v  a  2 s .  co m
        while (true) {
            //
            // Set up HTTP connection
            //
            GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.PROTOCOL,
                    "SocketServerListener secure=", secure, "waiting for a connection on socket");
            Socket socket = serverSocket.accept();
            GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.PROTOCOL,
                    "SocketServerListener secure=", secure, "got a connection");

            DefaultHttpServerConnection serverConnection = new DefaultHttpServerConnection();
            HttpParams params = new BasicHttpParams();
            serverConnection.bind(socket, params);

            InetSocketAddress remoteInetSocketAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
            InetSocketAddress localInetSocketAddress = (InetSocketAddress) socket.getLocalSocketAddress();

            String connectionName = "HTTPServerConnection" + Stack.nextTransactionId();
            String remoteHost = remoteInetSocketAddress.getAddress().getHostAddress();
            String remotePort = Integer.toString(remoteInetSocketAddress.getPort());
            String localHost = localInetSocketAddress.getAddress().getHostAddress();
            String localPort = Integer.toString(localInetSocketAddress.getPort());

            BIOChannelHttp connHttp = new BIOChannelHttp(connectionName, localHost, localPort, remoteHost,
                    remotePort, StackFactory.PROTOCOL_HTTP, secure);

            //
            // Start Server thread
            //
            BIOSocketServerHttp socketServerHttp = new BIOSocketServerHttp(serverConnection, connHttp);

            connHttp.setSocketServerHttp(socketServerHttp);
            StackFactory.getStack(StackFactory.PROTOCOL_HTTP).openChannel(connHttp);
        }
    } catch (Exception e) {
        GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.PROTOCOL, e,
                "Exception in SocketServerListener secure=" + secure);
    }

    GlobalLogger.instance().getApplicationLogger().warn(TextEvent.Topic.PROTOCOL,
            "SocketServerListener secure=", secure, "stopped");
}

From source file:org.pircbotx.IdentServer.java

/**
 * Waits for a client to connect to the ident server before making an
 * appropriate response./* w  ww .  j  av  a2 s. c  o m*/
 */
public void run() {
    log.info("IdentServer running on port " + serverSocket.getLocalPort());
    while (!serverSocket.isClosed()) {
        Socket socket = null;
        try {
            socket = serverSocket.accept();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(socket.getInputStream(), encoding));
            OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream(), encoding);
            InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();

            //Read first line and process
            String line = reader.readLine();
            String response = handleNextConnection(remoteAddress, line);
            if (response != null) {
                writer.write(response);
                writer.flush();
            }
        } catch (Exception e) {
            if (serverSocket.isClosed()) {
                log.debug("Server socket closed, exiting connection loop");
                return;
            } else
                //This is not from the server socket closing
                throw new RuntimeException("Exception encountered when opening user socket", e);
        } finally {
            //Close user socket
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                throw new RuntimeException("Exception encountered when closing user socket", e);
            }
        }
    }

    //Done with connection loop, can safely close the socket now
    if (!serverSocket.isClosed())
        try {
            close();
        } catch (IOException e) {
            log.error("Cannot close IdentServer socket", e);
        }
}

From source file:com.techcavern.pircbotz.IdentServer.java

/**
 * Waits for a client to connect to the ident server before making an
 * appropriate response.//from  www .java 2  s  .  c  o m
 */
public void run() {
    log.info("IdentServer running on port " + serverSocket.getLocalPort());
    //TODO: Multi-thread this
    while (!serverSocket.isClosed()) {
        Socket socket = null;
        try {
            socket = serverSocket.accept();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(socket.getInputStream(), encoding));
            OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream(), encoding);
            InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();

            //Read first line and process
            String line = reader.readLine();
            String response = handleNextConnection(remoteAddress, line);
            if (response != null) {
                writer.write(response);
                writer.flush();
            }
        } catch (Exception e) {
            if (serverSocket.isClosed()) {
                log.debug("Server socket closed, exiting connection loop");
                return;
            } else
                //This is not from the server socket closing
                throw new RuntimeException("Exception encountered when opening user socket");
        } finally {
            //Close user socket
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                throw new RuntimeException("Exception encountered when closing user socket");
            }
        }
    }

    //Done with connection loop, can safely close the socket now
    if (!serverSocket.isClosed())
        try {
            close();
        } catch (IOException e) {
            log.error("Cannot close IdentServer socket", e);
        }
}

From source file:org.structr.cloud.CloudConnection.java

public CloudConnection(final SecurityContext securityContext, final Socket socket,
        final CloudListener listener) {

    super("CloudConnection(" + socket.getRemoteSocketAddress() + ")");

    this.app = StructrApp.getInstance(securityContext);
    this.remoteAddress = socket.getInetAddress().getHostAddress();
    this.listener = listener;
    this.socket = socket;

    this.setDaemon(true);

    logger.log(Level.INFO, "New connection from {0}", socket.getRemoteSocketAddress());
}

From source file:org.apache.hadoop.hdfs.server.datanode.DataXceiver.java

public DataXceiver(Socket s, DataNode datanode, DataXceiverServer dataXceiverServer) {

    this.s = s;/*  w w w.ja  v  a2s  .  c  o m*/
    this.datanode = datanode;
    this.dataXceiverServer = dataXceiverServer;
    dataXceiverServer.childSockets.put(s, s);
    remoteAddress = s.getRemoteSocketAddress().toString();
    localAddress = s.getLocalSocketAddress().toString();
    LOG.debug("Number of active connections is: " + datanode.getXceiverCount());
}

From source file:com.predic8.membrane.core.rules.SSLProxy.java

@Override
public SSLContext getSslInboundContext() {
    return new SSLContext(new SSLParser(), router.getResolverMap(), router.getBaseLocation()) {

        @Override//  w w  w .jav  a 2s . c  o  m
        public Socket wrap(Socket socket, byte[] buffer, int position) throws IOException {
            int port = target.getPort();
            if (port == -1)
                port = getPort();

            StreamPump.StreamPumpStats streamPumpStats = router.getStatistics().getStreamPumpStats();
            String protocol = "SSL";

            Connection con = cm.getConnection(target.getHost(), port, connectionConfiguration.getLocalAddr(),
                    null, connectionConfiguration.getTimeout());

            con.out.write(buffer, 0, position);
            con.out.flush();

            String source = socket.getRemoteSocketAddress().toString();
            String dest = con.toString();
            final StreamPump a = new StreamPump(con.in, socket.getOutputStream(), streamPumpStats,
                    protocol + " " + source + " <- " + dest, SSLProxy.this);
            final StreamPump b = new StreamPump(socket.getInputStream(), con.out, streamPumpStats,
                    protocol + " " + source + " -> " + dest, SSLProxy.this);

            socket.setSoTimeout(0);

            String threadName = Thread.currentThread().getName();
            new Thread(a, threadName + " " + protocol + " Backward Thread").start();
            try {
                Thread.currentThread().setName(threadName + " " + protocol + " Onward Thread");
                b.run();
            } finally {
                try {
                    con.close();
                } catch (IOException e) {
                    log.debug("", e);
                }
            }
            throw new SocketException("SSL Forwarding Connection closed.");
        }
    };
}

From source file:com.hqme.cm.cache.StreamingServer.java

private void handleRequests() {
    // android.os.Debug.waitForDebugger();

    try {//from  w ww . j  av a2  s. c  o m
        Socket client = null;
        while (!isStopping)
            try {
                client = null;
                client = serverSocket.accept();

                // prevent connections from remote internet addresses; clients must playback from localhost sockets only
                SocketAddress socketAddress = client.getRemoteSocketAddress();
                if (InetSocketAddress.class.isInstance(socketAddress)) {
                    String hostName = ((InetSocketAddress) socketAddress).getHostName();
                    if (!"localhost".equalsIgnoreCase(hostName)) {
                        // UntenCacheService.debugLog(sTag, "handleRequests: client.getRemoteSocketAddress().getHostName(): %s", hostName);
                        client.close();
                        client = null;
                        continue;
                    }
                }
            } catch (IOException fault) {
                isStopping = true;
            } finally {
                synchronized (clientBox) {
                    if (isStopping) {
                        for (int i = 0; i < clientBox.length; i++) {
                            if (clientBox[i] != null && clientBox[i].thread != null
                                    && clientBox[i].thread.isAlive()) {
                                UntenCacheService.debugLog(sTag, "run: Stopping client # %d", i);
                                clientBox[i].handler.isStopRequested = true;
                            }
                        }
                    } else if (client != null) {
                        int i = 0;
                        for (i = 0; i < clientBox.length; i++) {
                            if (clientBox[i] == null || !clientBox[i].thread.isAlive()) {
                                clientBox[i] = new ClientBox();
                                clientBox[i].handler = new ClientHandler(client, i);
                                clientBox[i].thread = new Thread(clientBox[i].handler);
                                clientBox[i].thread.setDaemon(true);
                                clientBox[i].thread.start();
                                // UntenCacheService.debugLog(sTag, "handleRequests", "Accepted client # %d", i);
                                break;
                            }
                        }
                        if (i == clientBox.length) { // End with no slot for it.
                            client.close();
                        }
                    }
                }
            }
    } catch (Exception fault) {
        fault.printStackTrace();
    } finally {
        if (serverSocket != null) {
            try {
                serverSocket.close();
                serverSocket = null;
            } catch (Throwable ignore) {
            }
        }
        clientBox = null;
    }
}

From source file:com.clustercontrol.agent.Agent.java

/**
 * ??sendManagerDiscoveryInfo?/*w w  w .ja  va 2 s.co  m*/
 * TCP 24005?????????IP?
 * 
 * @throws Exception
 */
private String receiveManagerDiscoveryInfo() throws Exception {
    int default_port = 24005;
    String portStr = AgentProperties.getProperty("discovery.pingport", Integer.toString(default_port));
    int port = Integer.parseInt(portStr);
    if (port < 1 || port > 65535) {
        port = default_port;
    }
    ServerSocket servSock = null;
    Socket clntSock = null;

    final int BUFSIZE = 256;
    int tmpRecvMsgSize = 0;
    int recvMsgSize = 0;
    byte[] receiveBuf = new byte[BUFSIZE];
    String recvMsg = "";

    try {
        servSock = new ServerSocket(port);

        // ????
        clntSock = servSock.accept();
        m_log.info("connecting to " + clntSock.getRemoteSocketAddress().toString());

        InputStream in = clntSock.getInputStream();
        OutputStream out = clntSock.getOutputStream();

        while ((tmpRecvMsgSize = in.read(receiveBuf)) != -1) {
            out.write(receiveBuf, 0, tmpRecvMsgSize);
            recvMsgSize = tmpRecvMsgSize;
        }

        recvMsg = new String(receiveBuf, 0, recvMsgSize);
        m_log.info("receive message : " + recvMsg);
    } catch (Exception e) {
        m_log.warn("receiveManagerIp " + e.getClass().getSimpleName() + ", " + e.getMessage());
        throw e;
    } finally {
        try {
            if (clntSock != null) {
                clntSock.close();
            }
        } catch (Exception e) {
            m_log.warn("receiveManagerIp: " + e);
        }
        try {
            if (servSock != null) {
                servSock.close();
            }
        } catch (Exception e) {
            m_log.warn("receiveManagerIp: " + e);
        }
    }
    return recvMsg;
}