Example usage for java.net Socket getLocalAddress

List of usage examples for java.net Socket getLocalAddress

Introduction

In this page you can find the example usage for java.net Socket getLocalAddress.

Prototype

public InetAddress getLocalAddress() 

Source Link

Document

Gets the local address to which the socket is bound.

Usage

From source file:org.apache.hama.util.BSPNetUtils.java

/**
 * Like {@link NetUtils#connect(Socket, SocketAddress, int)} but also takes a
 * local address and port to bind the socket to.
 * //from w  ww.  j ava 2  s.  co 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) {
        socket.bind(localAddr);
    }

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

/**
 * {@inheritDoc}// w w  w.  j  a v  a  2s . c  om
 */
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:com.mirth.connect.server.util.ConnectorUtil.java

public static ConnectionTestResponse testConnection(String host, int port, int timeout, String localAddr,
        int localPort) throws Exception {
    Socket socket = null;
    InetSocketAddress address = null;
    InetSocketAddress localAddress = null;

    try {//from  w  w w . j  a v a2 s  .c o m
        address = new InetSocketAddress(host, port);

        if (StringUtils.isBlank(address.getAddress().getHostAddress()) || (address.getPort() < 0)
                || (address.getPort() > 65534)) {
            throw new Exception();
        }
    } catch (Exception e) {
        return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE, "Invalid host or port.");
    }

    if (localAddr != null) {
        try {
            localAddress = new InetSocketAddress(localAddr, localPort);

            if (StringUtils.isBlank(localAddress.getAddress().getHostAddress()) || (localAddress.getPort() < 0)
                    || (localAddress.getPort() > 65534)) {
                throw new Exception();
            }
        } catch (Exception e) {
            return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE,
                    "Invalid local host or port.");
        }
    }

    try {
        socket = new Socket();

        if (localAddress != null) {
            try {
                socket.bind(localAddress);
            } catch (Exception e) {
                return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE,
                        "Could not bind to local address: " + localAddress.getAddress().getHostAddress() + ":"
                                + localAddress.getPort());
            }
        }

        socket.connect(address, timeout);
        String connectionInfo = socket.getLocalAddress().getHostAddress() + ":" + socket.getLocalPort() + " -> "
                + address.getAddress().getHostAddress() + ":" + address.getPort();
        return new ConnectionTestResponse(ConnectionTestResponse.Type.SUCCESS,
                "Successfully connected to host: " + connectionInfo, connectionInfo);
    } catch (SocketTimeoutException ste) {
        return new ConnectionTestResponse(ConnectionTestResponse.Type.TIME_OUT, "Timed out connecting to host: "
                + address.getAddress().getHostAddress() + ":" + address.getPort());
    } catch (Exception e) {
        return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE, "Could not connect to host: "
                + address.getAddress().getHostAddress() + ":" + address.getPort());
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
}

From source file:org.pepstock.jem.gwt.server.connector.WebInterceptor.java

@Override
public void onConnect(Socket connectedSocket) throws IOException {
    LogAppl.getInstance().emit(NodeMessage.JEMC202I);
    PrintWriter out = null;/*from   w  ww . ja v a  2 s  .c om*/
    BufferedReader in = null;
    String address = null;
    try {
        // get the printer to use to send the request to the server
        out = new PrintWriter(new OutputStreamWriter(connectedSocket.getOutputStream(), CharSet.DEFAULT));
        // get the reader to use to read the response sent from the server
        in = new BufferedReader(new InputStreamReader(connectedSocket.getInputStream(), CharSet.DEFAULT));
        // is the ip seen from the server
        String ip = connectedSocket.getLocalAddress().getHostAddress();
        // is the port seen from the server
        int port = connectedSocket.getLocalPort();
        address = ip + ":" + port;
        // if it must read the keystore 
        // form servlet context
        if (readKeyStore) {
            readKeyStore();
        }
        // instantiate the jemProtocol that give the right request (Base64
        // encoded) from the given response
        Key symmetricKey = KeysUtil.getSymmetricKey(clusterKeystoreInfo);
        ClientLoginProtocol jemClientProtocol = new ClientLoginProtocol(symmetricKey);
        String request = jemClientProtocol.getRequestFromResponse(null, address, LoginRequest.JEM_WEB_USER);
        LogAppl.getInstance().emit(NodeMessage.JEMC203I, new String(Base64.decode(request), CharSet.DEFAULT));
        out.println(request);
        out.flush();
        String inputResponse;
        String outputRequest;
        while ((inputResponse = in.readLine()) != null) {
            outputRequest = jemClientProtocol.getRequestFromResponse(inputResponse, address,
                    LoginRequest.JEM_WEB_USER);
            LogAppl.getInstance().emit(NodeMessage.JEMC203I,
                    new String(Base64.decode(inputResponse), CharSet.DEFAULT));
            if (outputRequest != null) {
                LogAppl.getInstance().emit(NodeMessage.JEMC203I,
                        new String(Base64.decode(outputRequest), CharSet.DEFAULT));
            }
            if (jemClientProtocol.isConversationTerminated()) {
                break;
            }
            out.println(outputRequest);
            out.flush();
        }
    } catch (LoginProtocolException e) {
        LogAppl.getInstance().emit(NodeMessage.JEMC106W, e);
        throw new IOException(e.getMessage(), e);
    } catch (KeyException e) {
        LogAppl.getInstance().emit(NodeMessage.JEMC106W, e);
        throw new IOException(e.getMessage(), e);
    }
}

From source file:de.ecclesia.kipeto.RepositoryResolver.java

/**
 * Ermittelt anhand der Default-Repository-URL die IP-Adresse der
 * Netzwerkkarte, die Verbindung zum Repository hat.
 */// w ww. j a  v  a 2  s  .  com
private String determinateLocalIP() throws IOException {
    Socket socket = null;

    try {

        int port;
        String hostname;

        if (isSftp()) {
            port = 22;
            hostname = getHostname();
        } else {
            URL url = new URL(defaultRepositoryUrl);
            port = url.getPort() > -1 ? url.getPort() : url.getDefaultPort();
            hostname = url.getHost();
        }

        log.debug("Determinating local IP-Adress by connect to {}:{}", defaultRepositoryUrl, port);
        InetAddress address = Inet4Address.getByName(hostname);

        socket = new Socket();
        socket.connect(new InetSocketAddress(address, port), 3000);
        InputStream stream = socket.getInputStream();
        InetAddress localAddress = socket.getLocalAddress();
        stream.close();

        String localIp = localAddress.getHostAddress();

        log.info("Local IP-Adress is {}", localIp);

        return localIp;
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
}

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;//from   www  .ja v a2  s.c  o 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:com.sun.grizzly.http.jk.common.ChannelNioSocket.java

public boolean isSameAddress(MsgContext ep) {
    Socket s = (Socket) ep.getNote(socketNote);
    return isSameAddress(s.getLocalAddress(), s.getInetAddress());
}

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.  ja v  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:org.openhab.binding.samsungtv.internal.protocol.RemoteControllerLegacy.java

private void writeInitialInfo(Writer writer, Socket socket) throws RemoteControllerException {
    try {//from w  w w .  j av  a2s .c  om
        /* @formatter:off
        *
        * offset value and description
        * ------ ---------------------
        * 0x00   0x00 - datagram type?
        * 0x01   0x0013 - string length (little endian)
        * 0x03   "iphone.iapp.samsung" - string content
        * 0x16   0x0038 - payload size (little endian)
        * 0x18   payload
        *
        * Payload starts with 2 bytes: 0x64 and 0x00, then comes 3 strings
        * encoded with base64 algorithm. Every string is preceded by
        * 2-bytes field containing encoded string length.
        *
        * These three strings are as follow:
        *
        * remote control device IP, unique ID  value to distinguish
        * controllers, name  it will be displayed as controller name.
        *
        * @formatter:on
        */

        writer.append((char) 0x00);
        writeString(writer, APP_STRING);
        writeString(writer, createRegistrationPayload(socket.getLocalAddress().getHostAddress()));
        writer.flush();
    } catch (IOException e) {
        throw new RemoteControllerException(e);
    }
}