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:org.teleal.cling.transport.impl.apache.StreamServerImpl.java

public void run() {

    log.fine("Entering blocking receiving loop, listening for HTTP stream requests on: "
            + serverSocket.getLocalSocketAddress());
    while (!stopped) {

        try {//from  www. j  a va 2s .  c  o  m
            // Block until we have a connection
            Socket clientSocket = serverSocket.accept();
            log.fine("Incoming connection from: " + clientSocket.getInetAddress());
            // if (HTTPServerData.HOST != null
            // &&
            // !clientSocket.getInetAddress().getHostAddress().equals(HTTPServerData.HOST)
            // && !configuration.isExported()) {
            // clientSocket.close();
            // continue;
            // }
            // We have to force this fantastic library to accept HTTP
            // methods which are not in the holy RFCs.
            DefaultHttpServerConnection httpServerConnection = new DefaultHttpServerConnection() {
                @Override
                protected HttpRequestFactory createHttpRequestFactory() {
                    return new UpnpHttpRequestFactory();
                }
            };

            httpServerConnection.bind(clientSocket, globalParams);
            // Wrap the processing of the request in a UpnpStream
            UpnpStream connectionStream = new HttpServerConnectionUpnpStream(router.getProtocolFactory(),
                    httpServerConnection, globalParams);

            router.received(connectionStream);

        } catch (InterruptedIOException ex) {
            log.info("I/O has been interrupted, stopping receiving loop, bytes transfered: "
                    + ex.bytesTransferred);
            break;
        } catch (SocketException ex) {
            if (!stopped) {
                // That's not good, could be anything
                log.info("Exception using server socket: " + ex.getMessage());
            } else {
                // Well, it's just been stopped so that's totally fine and
                // expected
            }
            break;
        } catch (IOException ex) {
            log.info("Exception initializing receiving loop: " + ex.getMessage());
            break;
        }
    }

    try {
        log.fine("Receiving loop stopped");
        if (!serverSocket.isClosed()) {
            log.fine("Closing streaming server socket");
            serverSocket.close();
        }
    } catch (Exception ex) {
        log.info("Exception closing streaming server socket: " + ex.getMessage());
    }

}

From source file:net.vexelon.myglob.utils.TrustAllSocketFactory.java

/**
 * Prevents the reverse DNS lookup from being made. Fixed in Android 4.0, but still needs
 * workaround for earlier versions. //from  w  ww . jav  a 2 s .  co m
 * Source: http://code.google.com/p/android/issues/detail?id=13117#c14
 * @param socket
 * @param host
 */
private void injectHostname(Socket socket, String host) {
    try {
        Field field = InetAddress.class.getDeclaredField("hostName");
        field.setAccessible(true);
        field.set(socket.getInetAddress(), host);
    } catch (Exception ignored) {
        // uhm
    }
}

From source file:it.jnrpe.server.CBindingThread.java

@Override
public void run() {
    if (m_Logger.isInfoEnabled())
        m_Logger.info("LISTENING TO " + m_Binding.getIP() + ":" + m_Binding.getPort());

    try {/*from  w  w w .  ja  v a 2 s.  c  om*/
        while (!this.isInterrupted()) {
            Socket clientSocket = m_serverSocket.accept();
            if (clientSocket != null) {
                if (!canAccept(clientSocket.getInetAddress())) {
                    if (m_Logger.isInfoEnabled())
                        m_Logger.info("REFUSING CONNECTION FROM " + clientSocket.getInetAddress());

                    clientSocket.close();
                    continue;
                }

                if (m_Logger.isDebugEnabled())
                    m_Logger.trace("ACCEPTING CONNECTION FROM " + clientSocket.getInetAddress());

                //                JNRPEServerThread kk = new JNRPEServerThread(clientSocket);
                JNRPEServerThread kk = m_threadFactory.createNewThread(clientSocket);
                //                CJNRPEServer.getThreadTimeoutWatcher().watch(kk);
                kk.start();
            }
        }
    } catch (SocketException se) {
        // This exception is thrown when the server socket is closed.
        // Ignoring
    } catch (Exception e) {
        m_Logger.error("INTERNAL ERROR: " + e.getMessage(), e);
    }

    m_Logger.info("STOP LISTENING TO " + m_Binding.getIP() + ":" + m_Binding.getPort());
    exit();
}

From source file:org.pepstock.jem.node.https.RequestListener.java

@Override
public void run() {
    // starts here
    LogAppl.getInstance().emit(NodeMessage.JEMC046I, String.valueOf(serverSocket.getLocalPort()));
    boolean isForever = true;
    // ends only if interrupted
    while (isForever) {
        try {//from   ww w.  j a  v a  2s. c o m
            // Set up HTTP connection
            Socket socket = serverSocket.accept();
            // creates https connection
            HttpServerConnection conn = connectionFactory.createConnection(socket);
            // Start worker thread
            Worker w = new Worker(socket.getInetAddress(), httpService, conn);
            // puts on the pool.
            EXECUTOR_SERVICE.execute(w);
        } catch (InterruptedIOException e) {
            LogAppl.getInstance().emit(NodeMessage.JEMC004E, e);
            isForever = false;
        } catch (IOException e) {
            LogAppl.getInstance().emit(NodeMessage.JEMC004E, e);
            isForever = false;
        }
    }
}

From source file:net.pms.network.HTTPServer.java

@Override
public void run() {
    logger.info("Starting DLNA Server on host {} and port {}...", hostname, port);

    while (!stop) {
        try {//from   w w w .  j  av  a  2  s .  co m
            Socket socket = serverSocket.accept();
            InetAddress inetAddress = socket.getInetAddress();
            String ip = inetAddress.getHostAddress();
            // basic IP filter: solntcev at gmail dot com
            boolean ignore = false;

            if (configuration.getIpFiltering().allowed(inetAddress)) {
                logger.trace("Receiving a request from: " + ip);
            } else {
                ignore = true;
                socket.close();
                logger.trace("Ignoring request from: " + ip);
            }

            if (!ignore) {
                RequestHandler request = new RequestHandler(socket);
                Thread thread = new Thread(request, "Request Handler");
                thread.start();
            }
        } catch (ClosedByInterruptException e) {
            stop = true;
        } catch (IOException e) {
            logger.debug("Caught exception", e);
        } finally {
            try {
                if (stop && serverSocket != null) {
                    serverSocket.close();
                }

                if (stop && serverSocketChannel != null) {
                    serverSocketChannel.close();
                }
            } catch (IOException e) {
                logger.debug("Caught exception", e);
            }
        }
    }
}

From source file:jetbrains.exodus.util.ForkSupportIO.java

@NotNull
private Process spawnProcess() throws IOException {
    final Process process = builder.start();
    log.info("Waiting for connection...");
    final Socket connection = serverSocket.accept();
    log.info("Connection received from " + connection.getInetAddress().getHostName());
    log.info("Waiting to receive process Id");
    streamer = new Streamer(connection.getInputStream(), connection.getOutputStream());
    String idString = streamer.readString();
    processId = Integer.parseInt(idString);
    return process;
}

From source file:org.rifidi.edge.core.sensors.sessions.AbstractServerSocketSensorSession.java

@Override
protected void _connect() throws IOException {
    if (serverSocketPort < 1) {
        logger.info("Not starting server socket, since port < 1");
        return;//from  www .ja v  a  2 s  .  c  o  m
    }

    if (getStatus() == SessionStatus.CONNECTING || getStatus() == SessionStatus.PROCESSING) {
        logger.warn("Session already started");
        return;
    }
    setStatus(SessionStatus.CONNECTING);

    // create a new executor service that will handle each new request. Use
    // SynchronousQueue so that tasks will be rejected if there is no free
    // worker thread available
    executorService = new ThreadPoolExecutor(0, maxNumSensors, 5, TimeUnit.MINUTES,
            new SynchronousQueue<Runnable>());

    // open up server socket
    try {
        serverSocket = new ServerSocket(serverSocketPort);
    } catch (IOException e) {
        logger.error("Cannot start Alient Autonomous Sensor");
        disconnect();
        throw e;
    }
    logger.info(sensor.getID() + " listening on port " + serverSocket.getLocalPort()
            + ".  Maximum number of concurrent readers supported: " + maxNumSensors);
    setStatus(SessionStatus.PROCESSING);

    // while session is not closed, process each request
    while (!executorService.isShutdown()) {
        try {
            // wait on a new request
            Socket clientSocket = serverSocket.accept();
            logger.info("Accepted client at " + clientSocket.getInetAddress());

            // give the socket to the handler to do the dirty work
            ServerSocketSensorSessionReadThread handler = new ServerSocketSensorSessionReadThread(clientSocket,
                    getMessageParsingStrategyFactory(), getMessageProcessingStrategyFactory());
            try {
                executorService.execute(handler);
            } catch (RejectedExecutionException e) {
                logger.warn("Cannot create a handler thread for socket " + clientSocket.getInetAddress(), e);
                clientSocket.close();
            }
        } catch (IOException e) {
            // print an error message if we weren't the ones who caused the
            // problem
            if (!executorService.isShutdown()) {
                logger.error("Failed to start Alien Autonomous Handler", e);
            }
        }
    }
    logger.info("Stopping " + sensor.getID());
    setStatus(SessionStatus.CREATED);

}

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

public AbstractTcpConnection(Socket socket, boolean server, boolean lookupHost) {
    this.server = server;
    InetAddress inetAddress = socket.getInetAddress();
    if (inetAddress != null) {
        this.hostAddress = inetAddress.getHostAddress();
        if (lookupHost) {
            this.hostName = inetAddress.getHostName();
        } else {/*  w  w w . j a  v a2  s . c  o  m*/
            this.hostName = this.hostAddress;
        }
    }
    int port = socket.getPort();
    this.connectionId = this.hostName + ":" + port + ":" + UUID.randomUUID().toString();
    try {
        this.soLinger = socket.getSoLinger();
    } catch (SocketException e) {
    }
}

From source file:org.coltram.nsd.bonjour.BonjourProcessor.java

public void callAction(JSONObject object, String serviceId, final AtomConnection connection, String callBack)
        throws JSONException {
    final DiscoveredZCService bonjourService = topManager.getServiceManager().findBonjourService(serviceId);
    if (bonjourService == null) {
        log.info("no service with id " + serviceId + " in callAction");
        return;//from w  w  w  .jav  a 2  s.  c  o  m
    }
    if (bonjourService.isLocal()) {
        // find the LocalExposedBonjourService in question
        LocalExposedBonjourService localcbs = LocalExposedBonjourService.getServiceById(serviceId);
        // send the info to that service
        object.put("originAtom", connection.getId());
        localcbs.notifyListeners(object.toString());
    } else {
        try {
            Socket socket = bonjourService.getSocket();
            int replyPort = -1;
            final InetAddress inetAddress = socket.getInetAddress();
            if (callBack != null) {
                // wait for reply on the same socket
                ServerSocket serverSocket = connection.getServerSocket();
                replyPort = serverSocket.getLocalPort();
                log.finer("start server for reply " + serverSocket.getLocalPort());
                new Thread(new ReplyListener(serverSocket, connection.getConnection())).start();
                Thread.yield();
            }
            String ia = inetAddress.toString();
            if (ia.startsWith("/")) {
                ia = ia.substring(1);
            }
            object.put("address", LocalHost.name);
            object.put("replyPort", replyPort + "");
            object.put("originAtom", connection.getId());
            DataOutputStream dos = bonjourService.getSocketDOS();
            dos.writeBytes(object.toString() + "\n");
            dos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:gov.hhs.fha.nhinc.lift.proxy.client.ClientConnector.java

@Override
public void run() {
    /*/*from w w w. j a v  a  2 s .co  m*/
     * Accept a connection and tunnel messages through the proxy system.
     */
    Socket socket = null;
    try {
        Thread toProxyThread;
        Thread fromProxyThread;

        socket = server.accept();
        log.debug("Server accepting to socket " + socket.getInetAddress());
        Connector toProxy = new Connector(socket.getInputStream(), proxyConnection.getOutStream(), bufferSize);
        Connector fromProxy = new Connector(proxyConnection.getInStream(), socket.getOutputStream(),
                bufferSize);

        toProxyThread = new Thread(toProxy, "Client To Proxy");
        fromProxyThread = new Thread(fromProxy, "Client From Proxy");

        toProxyThread.start();
        fromProxyThread.start();

        log.debug("Waiting to finish " + toProxyThread.getName());
        toProxyThread.join();

    } catch (IOException e) {
        String errorMsg = "Problem in creating client to proxy connectors: " + e.getMessage();
        log.error(errorMsg);
        controller.reportFailure(proxyConnection.getToken().getRequest(), errorMsg);
    } catch (InterruptedException e) {
        String errorMsg = "Client to proxy communication thread interrupted: " + e.getMessage();
        log.error(errorMsg);
        controller.reportFailure(proxyConnection.getToken().getRequest(), errorMsg);
    } finally {
        if (socket != null) {
            try {
                log.debug("Closing socket " + socket.getInetAddress() + ": " + socket.getPort());
                // Also closes associated streams
                socket.close();
            } catch (IOException ex) {
                log.warn("Unable to close client to proxy socket: " + ex.getMessage());
            }
        }
        if (proxyConnection != null) {
            try {
                log.debug("Closing proxy connection " + proxyConnection.getSocket().getInetAddress() + ": "
                        + proxyConnection.getSocket().getPort());
                proxyConnection.close();
            } catch (IOException ex) {
                log.warn("Unable to close proxy connection: " + ex.getMessage());
            }
        }
        if (server != null) {
            try {
                log.debug("Closing client connection server" + server.getInetAddress() + ": "
                        + server.getLocalPort());
                server.close();
            } catch (IOException ex) {
                log.warn("Unable to close proxy connection: " + ex.getMessage());
            }
        }
    }
}