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.apporiented.hermesftp.server.AbstractFtpServer.java

/**
 * {@inheritDoc}//w ww.ja  v a 2s  .c o  m
 */
public void run() {
    setStatus(SERVER_STATUS_INIT);
    ServerSocket serverSocket = null;
    try {
        getUserManager().load();
        serverSocket = createServerSocket();
        serverSocket.setSoTimeout(DEFAULT_TIMEOUT);
        setStatus(SERVER_STATUS_READY);
        while (!isTerminated()) {
            Socket clientSocket;
            try {
                clientSocket = serverSocket.accept();
            } catch (SocketTimeoutException e) {
                continue;
            }

            /* Check blacklisted IP v4 addresses */

            InetAddress clientAddr = clientSocket.getInetAddress();
            InetAddress localAddr = clientSocket.getLocalAddress();

            log.info("Client requests connection. ClientAddr.: " + clientAddr + ", LocalAddr.: " + localAddr);

            String listKey = NetUtils.isIPv6(clientAddr) ? FtpConstants.OPT_IPV6_BLACK_LIST
                    : FtpConstants.OPT_IPV4_BLACK_LIST;
            String ipBlackList = getOptions().getString(listKey, "");

            if (NetUtils.checkIPMatch(ipBlackList, clientAddr)) {
                log.info("Client with IP address " + clientAddr.getHostAddress() + " rejected (blacklisted).");
                IOUtils.closeGracefully(clientSocket);
                continue;
            }

            /* Initialize session context */
            FtpSessionContext ctx = createFtpContext();
            ctx.check();
            ctx.setCreationTime(new Date());
            ctx.setClientSocket(clientSocket);
            FtpSession session = (FtpSession) getApplicationContext().getBean(BEAN_SESSION);
            session.setFtpContext(ctx);

            /* Start session */
            log.debug("Accepting connection to " + clientAddr.getHostAddress());
            session.start();
            registerSession(session);

        }
        setStatus(SERVER_STATUS_HALTED);
    } catch (IOException e) {
        setStatus(SERVER_STATUS_UNDEF);
        log.error(e, e);
    } finally {
        terminateAllClientSessions();
        IOUtils.closeGracefully(serverSocket);
    }

}

From source file:org.eredlab.g4.ccl.net.bsd.RExecClient.java

InputStream _createErrorStream() throws IOException {
    ServerSocket server;//ww w.j  ava  2  s .c o m
    Socket socket;

    server = _socketFactory_.createServerSocket(0, 1, getLocalAddress());

    _output_.write(Integer.toString(server.getLocalPort()).getBytes());
    _output_.write('\0');
    _output_.flush();

    socket = server.accept();
    server.close();

    if (__remoteVerificationEnabled && !verifyRemote(socket)) {
        socket.close();
        throw new IOException("Security violation: unexpected connection attempt by "
                + socket.getInetAddress().getHostAddress());
    }

    return (new SocketInputStream(socket, socket.getInputStream()));
}

From source file:org.gcaldaemon.core.ldap.LDAPListener.java

private final void processAccept(SelectionKey key) throws Exception {

    // Check TCP/IP access
    if (hosts != null || addresses != null) {
        Socket socket = ((SocketChannel) key.channel()).socket();
        InetAddress inetAddress = socket.getInetAddress();
        if (hosts != null) {
            String host = inetAddress.getHostName();
            if (host == null || host.length() == 0 || host.equals("127.0.0.1")) {
                host = "localhost";
            } else {
                host = host.toLowerCase();
                if (host.equals("localhost.localdomain")) {
                    host = "localhost";
                }//from  w  w w .j a  v a 2  s .  c  o  m
            }
            if (!isHostMatch(host)) {
                throw new Exception("Connection refused, forbidden hostname (" + host + ")!");
            }
        }
        if (addresses != null) {
            String address = inetAddress.getHostAddress();
            if (address == null || address.length() == 0) {
                address = "127.0.0.1";
            }
            if (!isAddressMatch(address)) {
                throw new Exception("Connection refused, forbidden IP-address (" + address + ")!");
            }
        }
    }
}

From source file:uk.ac.bbsrc.tgac.miso.integration.util.IntegrationUtils.java

/**
 * Sends a String message to a given host socket
 * //from ww w .  j  a v a2  s  . c  om
 * @param socket
 *          of type Socket
 * @param query
 *          of type String
 * @return String
 * @throws IntegrationException
 *           when the socket couldn't be created
 */
public static String sendMessage(Socket socket, String query) throws IntegrationException {
    BufferedWriter wr = null;
    BufferedReader rd = null;
    try {
        wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));

        // Send data
        wr.write(query + "\r\n");
        wr.flush();

        // Get response
        rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        wr.close();
        rd.close();

        String dirty = sb.toString();
        StringBuilder response = new StringBuilder();
        int codePoint;
        int i = 0;
        while (i < dirty.length()) {
            codePoint = dirty.codePointAt(i);
            if ((codePoint == 0x9) || (codePoint == 0xA) || (codePoint == 0xD)
                    || ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
                    || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
                    || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF))) {
                response.append(Character.toChars(codePoint));
            }
            i += Character.charCount(codePoint);
        }

        return response.toString().replace("\\\n", "").replace("\\\t", "");
    } catch (UnknownHostException e) {
        log.error("Cannot resolve host: " + socket.getInetAddress(), e);
        throw new IntegrationException(e.getMessage());
    } catch (IOException e) {
        log.error("Couldn't get I/O for the connection to: " + socket.getInetAddress(), e);
        throw new IntegrationException(e.getMessage());
    } finally {
        try {
            if (wr != null) {
                wr.close();
            }
            if (rd != null) {
                rd.close();
            }
        } catch (Throwable t) {
            log.error("close socket", t);
        }
    }
}

From source file:com.plotsquared.iserver.core.Worker.java

/**
 * Prepares a request, then calls {@link #handle}
 * @param remote Client socket/*from  w  w w  .j a v a 2 s.  c  o  m*/
 */
private void handle(final Socket remote) {
    // Used for metrics
    final Timer.Context timerContext = Server.getInstance().getMetrics().registerRequestHandling();
    if (CoreConfig.verbose) { // Do we want to output a load of useless information?
        server.log(Message.CONNECTION_ACCEPTED, remote.getInetAddress());
    }
    final BufferedReader input;
    { // Read the actual request
        try {
            input = new BufferedReader(new InputStreamReader(remote.getInputStream()), CoreConfig.Buffer.in);
            output = new BufferedOutputStream(remote.getOutputStream(), CoreConfig.Buffer.out);

            final List<String> lines = new ArrayList<>();
            String str;
            while ((str = input.readLine()) != null && !str.isEmpty()) {
                lines.add(str);
            }

            request = new Request(lines, remote);

            if (request.getQuery().getMethod() == HttpMethod.POST) {
                final int cl = Integer.parseInt(request.getHeader("Content-Length").substring(1));
                request.setPostRequest(PostRequest.construct(request, cl, input));
            }
        } catch (final Exception e) {
            e.printStackTrace();
            return;
        }
    }
    if (!server.silent) {
        server.log(request.buildLog());
    }
    handle();
    timerContext.stop();
}

From source file:org.fourthline.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 ww w.jav a 2  s. com

            // Block until we have a connection
            final Socket clientSocket = serverSocket.accept();

            // We have to force this fantastic library to accept HTTP methods which are not in the holy RFCs.
            final DefaultHttpServerConnection httpServerConnection = new DefaultHttpServerConnection() {
                @Override
                protected HttpRequestFactory createHttpRequestFactory() {
                    return new UpnpHttpRequestFactory();
                }
            };

            log.fine("Incoming connection from: " + clientSocket.getInetAddress());
            httpServerConnection.bind(clientSocket, globalParams);

            // Wrap the processing of the request in a UpnpStream
            UpnpStream connectionStream = new HttpServerConnectionUpnpStream(router.getProtocolFactory(),
                    httpServerConnection, globalParams) {
                @Override
                protected Connection createConnection() {
                    return new ApacheServerConnection(clientSocket, httpServerConnection);

                }
            };

            router.received(connectionStream);

        } catch (InterruptedIOException ex) {
            log.fine("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.fine("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.fine("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:org.gcaldaemon.core.http.HTTPListener.java

private final void checkAccess(Socket socket) throws IOException, Exception {
    if (hosts != null || addresses != null) {
        InetAddress inetAddress = socket.getInetAddress();
        if (hosts != null) {
            String host = inetAddress.getHostName();
            if (host == null || host.length() == 0 || host.equals("127.0.0.1")) {
                host = "localhost";
            } else {
                host = host.toLowerCase();
                if (host.equals("localhost.localdomain")) {
                    host = "localhost";
                }/*from  w ww .  j ava 2  s. co m*/
            }
            if (!isHostMatch(host)) {
                log.warn("Connection refused (" + host + " is a forbidden hostname)!");
                throw new Exception("forbidden hostname (" + host + ')');
            }
        }
        if (addresses != null) {
            String address = inetAddress.getHostAddress();
            if (address == null || address.length() == 0) {
                address = "127.0.0.1";
            }
            if (!isAddressMatch(address)) {
                log.warn("Connection refused (" + address + " is a forbidden address)!");
                throw new Exception("forbidden IP-address (" + address + ')');
            }
        }
    }
}

From source file:org.apache.xmlrpc.WebServer.java

/**
 * Checks incoming connections to see if they should be allowed.
 * If not in paranoid mode, always returns true.
 *
 * @param s The socket to inspect./*from  w  w  w. j  av  a2s. c  o  m*/
 * @return Whether the connection should be allowed.
 */
protected boolean allowConnection(Socket s) {
    if (!paranoid) {
        return true;
    }

    int l = deny.size();
    byte address[] = s.getInetAddress().getAddress();
    for (int i = 0; i < l; i++) {
        AddressMatcher match = (AddressMatcher) deny.elementAt(i);
        if (match.matches(address)) {
            return false;
        }
    }
    l = accept.size();
    for (int i = 0; i < l; i++) {
        AddressMatcher match = (AddressMatcher) accept.elementAt(i);
        if (match.matches(address)) {
            return true;
        }
    }
    return false;
}

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  .  co  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.apache.isis.objectstore.nosql.db.file.server.FileServer.java

private void startSyncing() {
    final String syncHost = config.getString("fileserver.sync-host", DEFAULT_HOST);
    final int syncPort = config.getInt("fileserver.sync-port", DEFAULT_SYNC_PORT);
    final int connectionTimeout = config.getInt("fileserver.connection.timeout", 5000);

    LOG.info("preparing to sync to secondary server on " + syncHost + " port " + syncPort);

    final InetAddress address;
    try {/*from  w ww .ja v a 2s.  co  m*/
        address = InetAddress.getByName(syncHost);
    } catch (final UnknownHostException e) {
        LOG.error("Unknown host " + syncHost, e);
        System.exit(0);
        return;
    }

    while (awaitConnections) {
        Socket socket = null;
        try {
            socket = new Socket(address, syncPort);
            LOG.info("sync connected to " + socket.getInetAddress().getHostAddress() + " port "
                    + socket.getLocalPort());

            final CRC32 crc32 = new CRC32();
            final DataOutput output = new DataOutputStream(
                    new CheckedOutputStream(socket.getOutputStream(), crc32));
            final DataInput input = new DataInputStream(socket.getInputStream());
            output.writeByte(INIT);
            long logId = input.readLong();
            do {
                final long nextLogId = logId + 1;
                final File file = Util.logFile(nextLogId);
                if (file.exists() && server.getLogger().isWritten(nextLogId)) {
                    logId++;

                    output.writeByte(RECOVERY_LOG);
                    crc32.reset();
                    output.writeLong(logId);

                    LOG.info("sending recovery file: " + file.getName());
                    final BufferedInputStream fileInput = new BufferedInputStream(new FileInputStream(file));

                    final byte[] buffer = new byte[8092];
                    int read;
                    while ((read = fileInput.read(buffer)) > 0) {
                        output.writeInt(read);
                        output.write(buffer, 0, read);
                    }
                    output.writeInt(0);

                    output.writeLong(crc32.getValue());
                }
                try {
                    Thread.sleep(300);
                } catch (final InterruptedException ignore) {
                }

                while (isQuiescent) {
                    try {
                        Thread.sleep(300);
                    } catch (final InterruptedException ignore) {
                    }
                }
            } while (awaitConnections);

        } catch (final ConnectException e) {
            LOG.warn("not yet connected to secondary server at " + syncHost + " port " + syncPort);
            try {
                Thread.sleep(connectionTimeout);
            } catch (final InterruptedException ignore) {
            }
        } catch (final IOException e) {
            LOG.error("start failure - networking not set up for " + syncHost, e);
            try {
                Thread.sleep(300);
            } catch (final InterruptedException ignore) {
            }
        } catch (final RuntimeException e) {
            LOG.error("start failure", e);
            try {
                Thread.sleep(300);
            } catch (final InterruptedException ignore) {
            }
        }
    }

}