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:ee.ria.xroad.proxy.clientproxy.FastestConnectionSelectingSSLSocketFactory.java

private SSLSocket wrapToSSLSocket(Socket socket) throws IOException {
    if (socket instanceof SSLSocket) {
        return (SSLSocket) socket;
    }//from   w  ww  .  ja v  a2 s.  co m

    Socket sslSocket = socketfactory.createSocket(socket, socket.getInetAddress().getHostName(),
            socket.getPort(), SystemProperties.isUseSslSocketAutoClose());
    if (sslSocket instanceof SSLSocket) {
        return (SSLSocket) sslSocket;
    }

    throw new CodedException(X_INTERNAL_ERROR, "Failed to create SSL socket");
}

From source file:com.adito.tunnels.agent.RemoteTunnel.java

public void run() {
    // Process destination host and port for replacement variables
    VariableReplacement r = new VariableReplacement();
    r.setLaunchSession(launchSession);/* ww w  .j ava2 s  .c  o  m*/
    String destHost = r.replace(tunnel.getDestination().getHost());

    ByteArrayWriter msg = new ByteArrayWriter();

    try {

        msg.writeInt(tunnel.getResourceId());
        msg.writeString(tunnel.getSourceInterface());
        msg.writeString(launchSession.getId());
        msg.writeString(tunnel.getSourceInterface());
        msg.writeInt(tunnel.getSourcePort());
        msg.writeString(destHost);
        msg.writeInt(tunnel.getDestination().getPort());

        Request request = new Request(TunnelingService.START_REMOTE_TUNNEL, msg.toByteArray());
        agent.sendRequest(request, false);

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    running = true;
    if (log.isInfoEnabled())
        log.info("Starting remote listener on " + tunnel.getSourcePort());
    try {
        while (running) {
            try {
                Socket s = listeningSocket.accept();
                if (log.isInfoEnabled())
                    log.info("Received new connection on " + tunnel.getSourcePort() + " from "
                            + s.getInetAddress());
                RemoteForwardingChannel channel = new RemoteForwardingChannel(this, s, tunnel, launchSession);
                try {
                    agent.openChannel(channel);
                } catch (ChannelOpenException e) {
                    log.error("Error opening channel. Remote tunnel remaining open but closing connection.", e);
                    try {
                        s.close();
                    } catch (IOException ioe) {
                    }
                }
            } catch (IOException e) {
                if (running) {
                    log.error("IO error waiting for connection, stopping remote tunnel.", e);
                }
            }
        }
    } finally {

        Request request = new Request(TunnelingService.STOP_REMOTE_TUNNEL, msg.toByteArray());
        try {
            agent.sendRequest(request, false);
        } catch (IOException e) {
        }

        Channel[] c = agent.getActiveChannels();
        if (c != null) {
            for (int i = 0; i < c.length; i++) {
                if (c[i] instanceof RemoteForwardingChannel) {
                    RemoteForwardingChannel rfc = (RemoteForwardingChannel) c[i];
                    if (rfc.getRemoteTunnel() == this && rfc.getConnection() != null) {
                        try {
                            rfc.close();
                        } catch (Throwable t) {
                            // TODO workaround for NPE
                            log.error("Failed to close channel.", t);
                        }
                    }
                }
            }
        }
        tunnelManager.removeRemoteTunnel(this);
        LaunchSessionFactory.getInstance().removeLaunchSession(launchSession);
        running = false;
    }
}

From source file:com.pispower.video.sdk.net.SimpleSSLSocketFactory.java

/**
 * Pre-ICS Android had a bug resolving HTTPS addresses. This workaround
 * fixes that bug.//  w  ww. j  av a2  s  . com
 * 
 * @param socket
 *            The socket to alter
 * @param host
 *            Hostname to connect to
 * @see <a
 *      href="https://code.google.com/p/android/issues/detail?id=13117#c14">https://code.google.com/p/android/issues/detail?id=13117#c14</a>
 */
@SuppressWarnings("deprecation")
private void injectHostname(Socket socket, String host) {
    try {
        if (Integer.valueOf(Build.VERSION.SDK) >= 4) {
            Field field = InetAddress.class.getDeclaredField("hostName");
            field.setAccessible(true);
            field.set(socket.getInetAddress(), host);
        }
    } catch (Exception ignored) {
    }
}

From source file:net.NetUtils.java

/**
 * This is a drop-in replacement for //from w ww  .j a va 2 s. co m
 * {@link Socket#connect(SocketAddress, int)}.
 * In the case of normal sockets that don't have associated channels, this 
 * just invokes <code>socket.connect(endpoint, timeout)</code>. If 
 * <code>socket.getChannel()</code> returns a non-null channel,
 * connect is implemented using Hadoop's selectors. This is done mainly
 * to avoid Sun's connect implementation from creating thread-local 
 * selectors, since Hadoop does not have control on when these are closed
 * and could end up taking all the available file descriptors.
 * 
 * @see java.net.Socket#connect(java.net.SocketAddress, int)
 * 
 * @param socket
 * @param endpoint 
 * @param timeout - timeout in milliseconds
 */
public static void connect(Socket socket, SocketAddress endpoint, int timeout) throws IOException {
    if (socket == null || endpoint == null || timeout < 0) {
        throw new IllegalArgumentException("Illegal argument for connect()");
    }

    SocketChannel ch = socket.getChannel();

    if (ch == null) {
        // let the default implementation handle it.
        socket.connect(endpoint, timeout);
    } else {
        SocketIOWithTimeout.connect(ch, endpoint, timeout);
    }

    // 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:org.java.plugin.boot.ControlThread.java

private synchronized boolean handleRequest(final Socket clientSocket) {
    debug("handling control request"); //$NON-NLS-1$
    if (!isValidRemoteHost(clientSocket.getInetAddress())) {
        warn("incoming connection to control socket registered" //$NON-NLS-1$
                + " from REMOTE address " + clientSocket.getInetAddress() //$NON-NLS-1$
                + ", attempt to execute command was IGNORED"); //$NON-NLS-1$
        try {/*from w  w  w  .  ja  va2s. co  m*/
            clientSocket.close();
        } catch (IOException e) {
            // ignore
        }
        return false;
    }
    debug("processing control request"); //$NON-NLS-1$
    boolean result = false;
    try {
        String commandResult;
        InputStream in = clientSocket.getInputStream();
        OutputStream out = null;
        try {
            StringBuilder command = new StringBuilder();
            byte[] buf = new byte[16];
            int len;
            while ((len = in.read(buf)) != -1) {
                command.append(new String(buf, 0, len));
            }
            clientSocket.shutdownInput();
            debug("got command - " + command); //$NON-NLS-1$
            if ("STOP".equals(command.toString())) { //$NON-NLS-1$
                stopApplication();
                result = true;
                commandResult = "OK: stop done"; //$NON-NLS-1$
            } else if (command.toString().startsWith("PING")) { //$NON-NLS-1$
                commandResult = "OK: " //$NON-NLS-1$
                        + command.substring("PING".length()); //$NON-NLS-1$
            } else {
                commandResult = "ERROR: unknown command"; //$NON-NLS-1$
            }
            //debug("command executed");
            //debug("sending command result - " + commandResult);
            out = clientSocket.getOutputStream();
            out.write(commandResult.getBytes());
            out.flush();
            clientSocket.shutdownOutput();
            //debug("command result sent");
        } finally {
            try {
                in.close();
            } catch (IOException ioe) {
                // ignore
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ioe) {
                    // ignore
                }
            }
        }
    } catch (IOException ioe) {
        error("error processing control request", ioe); //$NON-NLS-1$
    }
    return result;
}

From source file:any.Linker.java

public void serve(final int port) {
    logger.info("+SERVICE: started to serve");

    try {// www . j a  v a  2s . co m
        // Start the server socket (?)
        serverSocket = new ServerSocket(port);

        while (true) {
            final Socket socket = serverSocket.accept();
            logger.info(
                    socket.getInetAddress().getCanonicalHostName() + ":" + socket.getPort() + " is connected");

            IConnection conn = new Connection(Thread.currentThread().getName(), this, socket);
            namedCon.put(socket.getInetAddress().getCanonicalHostName() + ":" + socket.getPort(), conn);
            // namedCon.put( "host", conn);
            logger.info("+SERVICE: connected to client " + socket.getInetAddress().getCanonicalHostName() + ":"
                    + socket.getPort());
        }
    } catch (IOException e) {
        logger.error("+SERVICE, serve IO exception", e);
    } catch (InterruptedException e) {
        logger.error("+SERVICE, main loop interupted", e);
    }
}

From source file:com.fine47.http.SecureSocketFactory.java

/**
 * Pre-ICS Android had a bug resolving HTTPS addresses. This workaround
 * fixes that bug./*from   w  ww.  jav  a 2  s  .  c o m*/
 *
 * @param socket The socket to alter
 * @param host Hostname to connec to
 * @see <a href="https://code.google.com/p/android/issues/detail?id=13117#c14">Details about this workaround</a>
 */
private void injectHostname(Socket socket, String host) {
    if (14 > android.os.Build.VERSION.SDK_INT) {
        try {
            Field field = InetAddress.class.getDeclaredField("hostName");
            field.setAccessible(true);
            field.set(socket.getInetAddress(), host);
        } catch (Exception ignored) {
        }
    }
}

From source file:com.l2jfree.gameserver.geoeditorcon.GeoEditorListener.java

@Override
public void run() {
    Socket connection = null;
    try {/*from ww  w .j ava  2s.  c o m*/
        while (true) {
            connection = _serverSocket.accept();
            if (_geoEditor != null && _geoEditor.isWorking()) {
                _log.warn("Geoeditor already connected!");
                connection.close();
                continue;
            }
            _log.info("Received geoeditor connection from: " + connection.getInetAddress().getHostAddress());
            _geoEditor = new GeoEditorThread(connection);
            _geoEditor.start();
        }
    } catch (Exception e) {
        _log.info("GeoEditorListener: ", e);
        try {
            if (connection != null)
                connection.close();
        } catch (Exception e2) {
        }
    } finally {
        try {
            _serverSocket.close();
        } catch (IOException io) {
            _log.info("", io);
        }
        _log.warn("GeoEditorListener Closed!");
    }
}

From source file:br.ufc.mdcc.mpos.net.profile.PersistenceTcpServer.java

@Override
public void clientRequest(Socket connection) throws IOException {
    OutputStream output = connection.getOutputStream();
    InputStream input = connection.getInputStream();

    byte tempBuffer[] = new byte[1024 * 4];
    while (input.read(tempBuffer) != -1) {

        String data = new String(tempBuffer);
        if (data != null && data.contains("date")) {
            persistence(data, connection.getInetAddress().toString());

            String resp = "ok";
            output.write(resp.getBytes(), 0, resp.length());
            output.flush();/*from ww w  .  ja va 2 s  .com*/
        }
        Arrays.fill(tempBuffer, (byte) 0);
    }
    close(input);
    close(output);
}

From source file:com.zimbra.cs.mailclient.MailConnection.java

private SSLSocket newSSLSocket(Socket sock) throws IOException {
    return (SSLSocket) getSSLSocketFactory().createSocket(sock, sock.getInetAddress().getHostName(),
            sock.getPort(), false);//from   w  ww.j  a v a 2 s. c  o  m
}