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:ch.cyberduck.core.ftp.FTPClient.java

@Override
protected void _prepareDataSocket_(final Socket socket) throws IOException {
    if (preferences.getBoolean("ftp.tls.session.requirereuse")) {
        if (socket instanceof SSLSocket) {
            // Control socket is SSL
            final SSLSession session = ((SSLSocket) _socket_).getSession();
            if (session.isValid()) {
                final SSLSessionContext context = session.getSessionContext();
                context.setSessionCacheSize(preferences.getInteger("ftp.ssl.session.cache.size"));
                try {
                    final Field sessionHostPortCache = context.getClass()
                            .getDeclaredField("sessionHostPortCache");
                    sessionHostPortCache.setAccessible(true);
                    final Object cache = sessionHostPortCache.get(context);
                    final Method method = cache.getClass().getDeclaredMethod("put", Object.class, Object.class);
                    method.setAccessible(true);
                    method.invoke(cache, String.format("%s:%s", socket.getInetAddress().getHostName(),
                            String.valueOf(socket.getPort())).toLowerCase(Locale.ROOT), session);
                    method.invoke(cache, String.format("%s:%s", socket.getInetAddress().getHostAddress(),
                            String.valueOf(socket.getPort())).toLowerCase(Locale.ROOT), session);
                } catch (NoSuchFieldException e) {
                    // Not running in expected JRE
                    log.warn("No field sessionHostPortCache in SSLSessionContext", e);
                } catch (Exception e) {
                    // Not running in expected JRE
                    log.warn(e.getMessage());
                }/*from   w  ww .j a v  a  2  s.  co m*/
            } else {
                log.warn(String.format("SSL session %s for socket %s is not rejoinable", session, socket));
            }
        }
    }
}

From source file:com.buaa.cfs.utils.NetUtils.java

/**
 * Like {@link NetUtils#connect(Socket, SocketAddress, int)} but also takes a local address and port to bind the
 * socket to.//w  w w .jav  a2  s.  c  o m
 *
 * @param socket
 * @param endpoint  the remote address
 * @param localAddr the local address to bind the socket to
 * @param timeout   timeout in milliseconds
 */
public static void connect(Socket socket, SocketAddress endpoint, SocketAddress localAddr, int timeout)
        throws IOException {
    if (socket == null || endpoint == null || timeout < 0) {
        throw new IllegalArgumentException("Illegal argument for connect()");
    }

    SocketChannel ch = socket.getChannel();

    if (localAddr != null) {
        Class localClass = localAddr.getClass();
        Class remoteClass = endpoint.getClass();
        Preconditions.checkArgument(localClass.equals(remoteClass),
                "Local address %s must be of same family as remote address %s.", localAddr, endpoint);
        socket.bind(localAddr);
    }

    try {
        if (ch == null) {
            // let the default implementation handle it.
            socket.connect(endpoint, timeout);
        } else {
            //        SocketIOWithTimeout.connect(ch, endpoint, timeout);
        }
    } catch (SocketTimeoutException ste) {
        //      throw new ConnectTimeoutException(ste.getMessage());
    }

    // There is a very rare case allowed by the TCP specification, such that
    // if we are trying to connect to an endpoint on the local machine,
    // and we end up choosing an ephemeral port equal to the destination port,
    // we will actually end up getting connected to ourself (ie any data we
    // send just comes right back). This is only possible if the target
    // daemon is down, so we'll treat it like connection refused.
    if (socket.getLocalPort() == socket.getPort() && socket.getLocalAddress().equals(socket.getInetAddress())) {
        LOG.info("Detected a loopback TCP socket, disconnecting it");
        socket.close();
        throw new ConnectException("Localhost targeted connection resulted in a loopback. "
                + "No daemon is listening on the target port.");
    }
}

From source file:com.l2jfree.gameserver.status.GameStatusThread.java

public GameStatusThread(Socket client, long uptime, String StatusPW) throws IOException {
    _cSocket = client;//from  www  . j  a  v  a  2 s .  co  m
    _uptime = uptime;

    _print = new PrintWriter(_cSocket.getOutputStream());
    _read = new BufferedReader(new InputStreamReader(_cSocket.getInputStream()));

    if (!isValidIP(client)) {
        telnetOutput(5, "Connection attempt from " + client.getInetAddress().getHostAddress() + " rejected.");
        _cSocket.close();
        return;
    }

    telnetOutput(1, client.getInetAddress().getHostAddress() + " accepted!");
    _print.println("Welcome to the l2core Telnet Server...");
    _print.println("Please insert your Password!");
    _print.print("Password: ");
    _print.flush();
    String tmpLine = readLine();
    if (tmpLine == null) {
        _print.println("Error during Connection!");
        _print.println("Disconnected...");
        _print.flush();
        _cSocket.close();
        return;
    }

    if (tmpLine.compareTo(StatusPW) != 0) {
        _print.println("Incorrect Password!");
        _print.println("Disconnected...");
        _print.flush();
        _cSocket.close();
        return;
    }

    if (Config.ALT_TELNET) {
        _print.println("Password Correct!");
        _print.print("GM name: ");
        _print.flush();
        _gm = readLine();

        Connection con = null;
        try {
            con = L2DatabaseFactory.getInstance().getConnection();
            PreparedStatement stmt = con.prepareStatement(
                    "SELECT COUNT(*) FROM characters WHERE char_name = ? AND accesslevel >= 100");
            stmt.setString(1, _gm);
            ResultSet rs = stmt.executeQuery();
            if (!rs.next()) {
                _print.println("No GMs of that name, disconnected...");
                _print.flush();
                _cSocket.close();
                return;
            } else {
                _print.println("Welcome, " + _gm);
            }

            rs.close();
            stmt.close();
        } catch (Exception e) {
            _print.println("Error, disconnected...");
            _print.flush();
            _cSocket.close();
        } finally {
            L2DatabaseFactory.close(con);
        }

        telnetOutput(4, _gm + " successfully connected to Telnet.");
    } else {
        _print.println("Connection accepted... Welcome!");
    }

    _print.println("[l2core telnet console]");
    _print.print("");
    _print.flush();
    start();
}

From source file:org.eclipse.jubula.communication.Communicator.java

/**
 * Initializes the given connection and socket, adding necessary listeners
 * and starting to read the input stream of the socket.
 * /*from   w ww.ja  v  a 2 s.  co m*/
 * @param conn The connection to initialize.
 * @param socket The socket associated with the connection.
 */
private void setup(Connection conn, Socket socket) {
    // add listener
    conn.addMessageHandler(m_connectionListener);
    conn.addErrorHandler(m_errorListener);
    // set an exceptionHandler
    conn.setExceptionHandler(getExceptionHandler());
    // start reading from connection
    String id = socket.toString();
    conn.startReading(id);
    fireConnectionGained(socket.getInetAddress(), socket.getPort());
}

From source file:node.Mailbox.java

/**
 * main loop//from   ww  w  . j  av a2s.  c o m
 */
@Override
public void run() {
    Socket socket = null;
    // set up server socket
    try {
        if (backlog == 0) {
            serverSocket = new ServerSocket(port);
        } else {
            serverSocket = new ServerSocket(port, backlog);
        }
        serverSocket.setSoTimeout(100);
        println("Opened up server socket on port " + port);
    } catch (SocketException e) {
        Control.logOneTime(e.getLocalizedMessage(), Level.SEVERE);
        println(e.getLocalizedMessage());
        System.exit(-1);
    } catch (IOException e) {
        Control.logOneTime(
                "Mailbox error: could not listen on port " + port + ". stacktrace: " + e.getLocalizedMessage(),
                Level.SEVERE);
        e.printStackTrace();
        log.severe(ExceptionUtils.getStackTrace(e));
        System.exit(-1);
    }
    // enter main loop
    while (!shutdown) {
        if (REPORT)
            reportSend.add(report());
        println(report().toJSONString());

        // block until a connection is accepted
        println("Waiting for a connection");
        try {
            socket = serverSocket.accept();
            InetAddress inetaddr = socket.getInetAddress();

            println("Received connection from " + inetaddr);
            // get the message id, then call the appropriate message handler
            acceptMessage(socket);
            // close the socket
            socket.close();
        } catch (SocketTimeoutException e) {
            println("No connection: socket timed out", true);
        } catch (ConnectException e) {
            println("Caught ConnectException", true);
        } catch (SocketException e) {
            println("Caught SocketException", true);
        } catch (IOException e) {
            e.printStackTrace();
            log.severe(ExceptionUtils.getStackTrace(e));
        }

        // See if we have any messages to send
        if (msgsSend.size() > 0)
            println("Have " + msgsSend.size() + " messages to send");
        while (msgsSend.size() > 0) {
            MessageWrapper<AbstractMessage> currentMsg = msgsSend.remove();
            println("Current message: " + currentMsg.toString());
            NodeListEntry nle_dest = currentMsg.nle;
            String destID = currentMsg.destID;
            printMessageSize(currentMsg);
            currentMsg.msg.scheduleSend(nodeList, destID, nle_dest);
            println("Mailbox: Message of type " + currentMsg.msg.msgType + " with id# " + currentMsg.msg.msgID
                    + " scheduled for sending to " + nle_dest.toString());
        }
        // check if it's time to shut down (signaled from Control)
        if (shutdown) {
            // write a log message, then exit
            // serverSocket.close()
            println("Mailbox exited");
            return;
        }
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
            log.severe(ExceptionUtils.getStackTrace(e));
        }
    }
}

From source file:org.unitime.timetable.solver.remote.SolverRegisterService.java

public void run() {
    iStartTime = new Date();
    try {//from   www  .  ja  v a  2s.c o m
        ConnectionFactory.init(ApplicationProperties.getProperties(), ApplicationProperties.getDataFolder());
        try {
            while (true) {
                try {
                    iServerSocket = ConnectionFactory.getServerSocketFactory().createServerSocket(Integer
                            .parseInt(ApplicationProperties.getProperty("tmtbl.solver.register.port", "9998")));
                    sLog.info("Service is running at " + iServerSocket.getInetAddress().getHostName() + ":"
                            + iServerSocket.getLocalPort());
                    break;
                } catch (BindException e) {
                    try {
                        sLog.warn("Prior instance of service still running");
                        Socket socket = ConnectionFactory.getSocketFactory().createSocket("localhost",
                                Integer.parseInt(ApplicationProperties.getProperty("tmtbl.solver.register.port",
                                        "9998")));
                        RemoteIo.writeObject(socket, "quit");
                        Object answer = RemoteIo.readObject(socket);
                        sLog.warn("quit command sent, answer: " + answer);
                        socket.close();
                    } catch (Exception f) {
                        sLog.warn("Unable to connect to prior instance", f);
                    }
                    sleep(1000);
                }
            }
        } catch (IOException io) {
            sLog.error("Unable to start service, reason: " + io.getMessage(), io);
            return;
        }
        while (!iServerSocket.isClosed()) {
            try {
                Socket socket = iServerSocket.accept();
                socket.setKeepAlive(true);
                sLog.debug("Client " + socket.getInetAddress() + " connected.");
                (new Thread(new SolverConnection(socket))).start();
            } catch (Exception e) {
                if (!iServerSocket.isClosed())
                    sLog.warn("Unable to accept new connection, reason:" + e.getMessage(), e);
            }
        }
    } catch (Exception e) {
        sLog.error("Unexpected exception occured, reason: " + e.getMessage(), e);
    } finally {
        try {
            if (iServerSocket != null && !iServerSocket.isClosed())
                iServerSocket.close();
        } catch (Exception e) {
            sLog.warn("Unable to close socket, reason: " + e.getMessage(), e);
        }
    }
}

From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java

/**
 * Return fake, temporary DistributedMember to represent the other vm this vm is connecting to
 * //from  w w  w  .j a va  2 s . c  om
 * @param sock the socket this handshake is operating on
 * @return temporary id to reprent the other vm
 */
private DistributedMember getIDForSocket(Socket sock) {
    return new InternalDistributedMember(sock.getInetAddress(), sock.getPort(), false);
}

From source file:org.apache.tomcat.util.net.PoolTcpEndpoint.java

public void runIt(Object perThrData[]) {

    // Create per-thread cache
    if (endpoint.isRunning()) {
        Socket s = null;
        try {/* www. ja va 2  s  .  c o  m*/
            s = endpoint.acceptSocket();
        } finally {
            // Continue accepting on another thread...
            if (endpoint.isRunning()) {
                endpoint.tp.runIt(this);
            }
        }
        if (null != s) {

            TcpConnection con = null;
            int step = 1;
            try {

                // 1: Set socket options: timeout, linger, etc
                endpoint.setSocketOptions(s);

                // 2: SSL handshake
                step = 2;
                if (endpoint.getServerSocketFactory() != null) {
                    endpoint.getServerSocketFactory().handshake(s);
                }

                // 3: Process the connection
                step = 3;
                con = (TcpConnection) perThrData[0];
                con.setEndpoint(endpoint);
                con.setSocket(s);
                endpoint.getConnectionHandler().processConnection(con, (Object[]) perThrData[1]);

            } catch (SocketException se) {
                endpoint.log
                        .error("Remote Host " + s.getInetAddress() + " SocketException: " + se.getMessage());
                // Try to close the socket
                try {
                    s.close();
                } catch (IOException e) {
                }
            } catch (Throwable t) {
                if (step == 2) {
                    endpoint.log.debug("Handshake failed", t);
                } else {
                    endpoint.log.error("Unexpected error", t);
                }
                // Try to close the socket
                try {
                    s.close();
                } catch (IOException e) {
                }
            } finally {
                if (con != null) {
                    con.recycle();
                }
            }
        }
    }
}

From source file:org.apache.hadoop.hive.service.HSSessionItem.java

public HSSessionItem(HSAuth auth, String sessionName, TTransport trans) throws FileNotFoundException {

    this.jobid = 0;
    this.auth = auth;
    this.sessionName = sessionName;
    this.home = ".";
    this.runable = null;
    this.jr = null;
    this.config = new SessionConfig(jobType.ONESHOT);
    this.jobStatus = HSSessionItem.JobStatus.INIT;
    this.date = new Date();
    this.opdate = this.date;
    if (SessionState.get() != null) {
        this.to = SessionState.get().getConf().getIntVar(HiveConf.ConfVars.HIVESESSIONTIMEOUT);
        if (this.to > 7200 || this.to < 0) {
            this.to = 60;
        }/* w  w  w.j  a v  a 2  s.co m*/
    } else {
        this.to = 7200;
    }

    this.transSet = new HashSet();
    if (trans != null)
        transSet.add(trans);
    l4j.debug("HSSessionItem created");
    status = SessionItemStatus.NEW;

    l4j.debug("Wait for NEW->READY transition");
    l4j.debug("NEW->READY transition complete");

    queryInfo = new HashMap<Integer, GregorianCalendar>();
    this.current_query_count = 0;

    InetAddress localhost = null;
    try {
        localhost = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    if (localhost != null)
        hostip = localhost.getHostAddress();

    try {
        TSocket tSocket = (TSocket) trans;
        Socket socket = tSocket.getSocket();
        InetAddress addr = socket.getInetAddress();
        this.clientip = addr.getHostAddress();
        l4j.debug("client address: " + addr.getHostAddress() + " client port: " + socket.getPort());
    } catch (Exception e) {
        l4j.debug("get IP, PORT failed in create session");
    }

    if ((conf_file_loc == null) || conf_file_loc.length() == 0) {
        return;
    }

    File f = new File(conf_file_loc);
    if (!f.exists()) {
        if (!f.mkdir()) {
            return;
        }
    }

    try {
        sessionFileName = conf_file_loc + "/" + sessionName + ".txt";
        File thefile = new File(sessionFileName);
        if (!thefile.exists()) {
            dayLogStream = new PrintWriter(new FileWriter(sessionFileName, true));
        } else {
            dayLogStream = new PrintWriter(new FileWriter(sessionFileName, true));
            dayLogStream.print("+++++++++++++++++++++++++++++++++++++++++++++++++++");
            dayLogStream.print('\n');
            dayLogStream.print("A new session is appended here!  ");
            dayLogStream.print('\n');
            Calendar rightNow = Calendar.getInstance();
            Date time = rightNow.getTime();
            dayLogStream.print(time.toString());
            dayLogStream.print('\n');
            dayLogStream.print("+++++++++++++++++++++++++++++++++++++++++++++++++++");
            dayLogStream.print('\n');
        }
    } catch (Exception ex) {
    }
}

From source file:org.sakaiproject.antivirus.impl.ClamAVScanner.java

protected void doScan(InputStream in) throws VirusScanIncompleteException, VirusFoundException {
    logger.debug("doingScan!");
    Socket socket = null;
    String virus = null;//from ww w. j ava2s  .com
    long start = System.currentTimeMillis();
    //this could be a null or zero lenght stream
    if (in == null) {
        return;
    }

    try {
        socket = getClamdSocket();
    } catch (UnknownHostException e) {
        logger.error("could not connect to host for virus check: " + e);
        throw new VirusScanIncompleteException(SCAN_INCOMPLETE_MSG);
    }
    if (socket == null || !socket.isConnected()) {
        logger.warn("scan is inclomplete!");
        throw new VirusScanIncompleteException(SCAN_INCOMPLETE_MSG);
    }
    BufferedReader reader = null;
    PrintWriter writer = null;
    Socket streamSocket = null;
    boolean virusFound = false;
    try {

        // prepare the reader and writer for the commands
        boolean autoFlush = true;
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "ASCII"));
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),
                autoFlush);
        // write a request for a port to use for streaming out the data to scan
        writer.println("STREAM");

        // parse and get the "stream" port#
        int streamPort = getStreamPortFromAnswer(reader.readLine());

        // get the "stream" socket and the related (buffered) output stream
        streamSocket = new Socket(socket.getInetAddress(), streamPort);
        OutputStream os = streamSocket.getOutputStream();

        // stream out the message to the scanner
        int data;
        // -1 signals the end of the data stream
        while ((data = in.read()) > -1) {
            os.write(data);
        }
        os.flush();
        os.close();
        streamSocket.close();

        String logMessage = "";
        String answer = null;
        for (int i = 0; i < 100; ++i) {
            answer = reader.readLine();
            if (answer != null) {
                answer = answer.trim();

                // if a virus is found the answer will be '... FOUND'
                if (answer.substring(answer.length() - FOUND_STRING.length()).equals(FOUND_STRING)) {
                    virusFound = true;
                    logMessage = answer + " (by virus scanner)";
                    //virus = answer.substring(answer.indexOf(":" + 1));
                    virus = answer.substring(0, answer.indexOf(FOUND_STRING)).trim();
                    logger.debug(logMessage);
                } else {
                    logger.debug("no virus found: " + answer);
                }
            } else {
                break;
            }
        }
        long finish = System.currentTimeMillis();
        logger.debug("Content scanned in " + (finish - start));
    } catch (UnsupportedEncodingException e) {
        logger.error("Exception caught calling CLAMD on " + socket.getInetAddress() + ": " + e.getMessage());
        throw new VirusScanIncompleteException(SCAN_INCOMPLETE_MSG, e);
    } catch (IOException e) {
        //we expect a connection reset if we tried to send too much data to clamd
        if ("Connection reset".equals(e.getMessage())) {
            logger.warn("Clamd reset the connection maybe due to the file being too large");
            return;
        }
        logger.error("Exception caught calling CLAMD on " + socket.getInetAddress() + ": " + e.getMessage());
        throw new VirusScanIncompleteException(SCAN_INCOMPLETE_MSG, e);

    } finally {

        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
            }
        }
        if (writer != null) {
            writer.close();
        }
        if (streamSocket != null) {
            try {
                streamSocket.close();
            } catch (IOException e) {

            }
        }
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {

            }
        }

    }
    if (virusFound) {
        logger.info("Virus detected!: " + virus);
        throw new VirusFoundException(virus);
    }

}