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.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.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 a2  s .  c  o  m

    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:net.timewalker.ffmq4.listeners.tcp.io.TcpListener.java

@Override
public void run() {
    try {/*from ww  w .  j a v a 2 s. c om*/
        log.debug("Waiting for clients [" + getName() + "]");
        while (!stopRequired) {
            Socket clientSocket = serverSocket.accept();

            // Enforce listener capacity
            int activeClients = getActiveClients();
            if (activeClients >= listenerCapacity) {
                log.warn("Listener is full (max=" + listenerCapacity + "), dropping new connection attempt.");
                try {
                    clientSocket.close();
                } catch (Exception e) {
                    log.error("Cannot close incoming connection", e);
                }
                continue;
            }

            String clientId = UUIDProvider.getInstance().getShortUUID();
            log.debug("Accepting a new client from " + clientSocket.getInetAddress().getHostAddress() + " ("
                    + (activeClients + 1) + ") : " + clientId + " [" + getName() + "]");
            try {
                ClientProcessor processor = createProcessor(clientId, clientSocket);
                registerClient(processor);
                processor.start();
            } catch (Exception e) {
                try {
                    clientSocket.close();
                } catch (Exception ex) {
                    log.error("Could not close socket [" + getName() + "]", ex);
                }

                log.error("Client failed : " + clientId + " [" + getName() + "]", e);
            }
        }
    } catch (Exception e) {
        if (!stopRequired)
            log.fatal("Server failed [" + getName() + "]", e);
    }
}

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).// w  w w  .  j a v  a 2 s  .c  om
 */
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);
    }
}

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)
 *//*  ww  w.j  av a  2s  .c  o  m*/
public WebSocketProxy(Socket localSocket, Socket remoteSocket) {
    this(localSocket, remoteSocket, remoteSocket.getInetAddress().getHostName(), remoteSocket.getPort());
}

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

private CachingDataXceiver(Socket s, SocketInputWrapper socketInput, DataNode datanode,
        CachingDataXceiverServer dataXceiverServer, BlockCache blockCache) throws IOException {

    super(new DataInputStream(new BufferedInputStream(socketInput, HdfsConstants.SMALL_BUFFER_SIZE)));

    this.s = s;//  ww  w  .  j  av a 2 s  . co m
    this.socketInputWrapper = socketInput;
    this.isLocal = s.getInetAddress().equals(s.getLocalAddress());
    this.datanode = datanode;
    this.dnConf = datanode.getDnConf();
    this.dataXceiverServer = dataXceiverServer;
    this.blockCache = blockCache;
    remoteAddress = s.getRemoteSocketAddress().toString();
    localAddress = s.getLocalSocketAddress().toString();

    if (LOG.isDebugEnabled()) {
        LOG.debug("Number of active connections is: " + datanode.getXceiverCount());
    }
}

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   ww w  .  ja  va 2  s  .  c  om*/
 * 
 * @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:com.l2jfree.gameserver.status.GameStatusThread.java

private boolean isValidIP(Socket client) {
    boolean result = false;

    String clientStringIP = client.getInetAddress().getHostAddress();

    telnetOutput(1, "Connection from: " + clientStringIP);

    // read and loop thru list of IPs, compare with newIP
    if (Config.DEVELOPER)
        telnetOutput(2, "");

    try {/*from ww w  . j  a  v a 2 s . c  om*/
        L2Properties telnetSettings = new L2Properties(L2AutoInitialization.TELNET_FILE);

        String HostList = telnetSettings.getProperty("ListOfHosts", "127.0.0.1,localhost");

        if (Config.DEVELOPER)
            telnetOutput(3, "Comparing ip to list...");

        // compare
        String ipToCompare = null;
        for (String ip : HostList.split(",")) {
            if (!result) {
                ipToCompare = InetAddress.getByName(ip).getHostAddress();
                if (clientStringIP.equals(ipToCompare))
                    result = true;
                if (Config.DEVELOPER)
                    telnetOutput(3, clientStringIP + " = " + ipToCompare + "(" + ip + ") = " + result);
            }
        }
    } catch (IOException e) {
        if (Config.DEVELOPER)
            telnetOutput(4, "");
        telnetOutput(1, "Error: " + e);
    }

    if (Config.DEVELOPER)
        telnetOutput(4, "Allow IP: " + result);
    return result;
}

From source file:com.LaunchKeyManager.http.AsyncHttpClient.java

private SocketFactory workAroundReverseDnsBugInHoneycombAndEarlier() {
    // Android had a bug where HTTPS made reverse DNS lookups (fixed in Ice Cream Sandwich)
    // http://code.google.com/p/android/issues/detail?id=13117
    return new LayeredSocketFactory() {
        SSLSocketFactory delegate = SSLSocketFactory.getSocketFactory();

        @Override/*from  ww  w.  j  a  v a  2s.  c om*/
        public Socket createSocket() throws IOException {
            return delegate.createSocket();
        }

        @Override
        public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort,
                HttpParams params) throws IOException {
            return delegate.connectSocket(sock, host, port, localAddress, localPort, params);
        }

        @Override
        public boolean isSecure(Socket sock) throws IllegalArgumentException {
            return delegate.isSecure(sock);
        }

        @Override
        public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
            injectHostname(socket, host);
            return delegate.createSocket(socket, host, port, autoClose);
        }

        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) {
            }
        }
    };
}

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 www .j av a  2 s.  c o  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();
    }
}