Example usage for java.net Socket bind

List of usage examples for java.net Socket bind

Introduction

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

Prototype

public void bind(SocketAddress bindpoint) throws IOException 

Source Link

Document

Binds the socket to a local address.

Usage

From source file:com.googlecode.xremoting.core.commonshttpclient.ssl.AuthSSLProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the given time limit.
 * <p>//  w w  w .j a  v a 2 s .c o m
 * To circumvent the limitations of older JREs that do not support connect timeout a
 * controller thread is executed. The controller thread attempts to create a new socket
 * within the given limit of time. If socket constructor does not return until the
 * timeout expires, the controller terminates and throws an {@link ConnectTimeoutException}
 * </p>
 *
 * @param host the host name/IP
 * @param port the port on the host
 * @param localAddress the local host name/IP to bind the socket to
 * @param localPort the port on the local machine
 * @param params {@link HttpConnectionParams Http connection parameters}
 *
 * @return Socket a new socket
 *
 * @throws IOException if an I/O error occurs while creating the socket
 * @throws UnknownHostException if the IP address of the host cannot be
 * determined
 */
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    int timeout = params.getConnectionTimeout();
    SocketFactory socketfactory = getSSLContext().getSocketFactory();
    if (timeout == 0) {
        Socket socket = socketfactory.createSocket(host, port, localAddress, localPort);
        doPreConnectSocketStuff(socket);
        return socket;
    } else {
        Socket socket = socketfactory.createSocket();
        doPreConnectSocketStuff(socket);
        SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);

        if (timeout > 0 && socket.getSoTimeout() == 0) {
            // force SO timeout if not set so we don't freeze forever
            // during a handshake
            socket.setSoTimeout(timeout);
        }

        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
        return socket;
    }
}

From source file:com.devoteam.srit.xmlloader.http.bio.BIOChannelHttp.java

/** Open a connexion to each Stack */
public boolean open() throws Exception {
    if (this.secure) {
        StatPool.beginStatisticProtocol(StatPool.CHANNEL_KEY, StatPool.BIO_KEY, StackFactory.PROTOCOL_TLS,
                StackFactory.PROTOCOL_HTTP);
    } else {//  w w  w .j a v a  2s  .c  o  m
        StatPool.beginStatisticProtocol(StatPool.CHANNEL_KEY, StatPool.BIO_KEY, StackFactory.PROTOCOL_TCP,
                StackFactory.PROTOCOL_HTTP);
    }

    this.startTimestamp = System.currentTimeMillis();

    if (null != this.socketServerHttp) {
        ThreadPool.reserve().start((BIOSocketServerHttp) socketServerHttp);
    } else {

        String host = this.getRemoteHost();
        int port = this.getRemotePort();

        DefaultHttpClientConnection defaultHttpClientConnection = new DefaultHttpClientConnection();

        Socket socket;

        if (this.secure) {
            // Create a trust manager that does not validate certificate chains like the default TrustManager
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    //No need to implement.
                }

                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    //No need to implement.
                }
            } };

            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, null);

            socket = sslContext.getSocketFactory().createSocket();
            // read all properties for the TCP socket 
            Config.getConfigForTCPSocket(socket, true);
        } else {
            //
            // Create a TCP non secure socket
            //                
            socket = new Socket();
            // read all properties for the TCP socket 
            Config.getConfigForTCPSocket(socket, false);
        }

        //
        // Bind the socket to the local address
        //
        String localHost = this.getLocalHost();
        int localPort = initialLocalport;

        if (null != localHost) {
            socket.bind(new InetSocketAddress(localHost, localPort));
        } else {
            socket.bind(new InetSocketAddress(localPort));
        }

        socket.setReceiveBufferSize(65536);
        socket.connect(new InetSocketAddress(host, port));

        this.setLocalPort(socket.getLocalPort());

        HttpParams params = new BasicHttpParams();
        defaultHttpClientConnection.bind(socket, params);

        this.socketClientHttp = new BIOSocketClientHttp(defaultHttpClientConnection, this);

        ThreadPool.reserve().start((BIOSocketClientHttp) socketClientHttp);
    }
    return true;
}

From source file:com.delphix.session.test.ServiceTest.java

/**
 * Scan for an unused port./*from w  ww  . j  a v a 2  s.  c o  m*/
 */
private int portScan() {
    int localPort = (int) (Math.random() * 1000) + 62626;

    do {
        Socket socket = new Socket();

        try {
            socket.setReuseAddress(true);
            socket.bind(new InetSocketAddress(localPort));
            assertTrue(socket.isBound());
            break;
        } catch (IOException e) {
            logger.infof(e, "failed to bind to port %d - try next", localPort);
            localPort++;
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                fail("failed to close socket", e);
            }
        }
    } while (localPort < 65536);

    if (localPort >= 65536) {
        fail("failed to find unused port");
    }

    logger.infof("unused local port %d found", localPort);

    return localPort;
}

From source file:com.atomicleopard.thundr.ftp.commons.FTPClient.java

/**
 * Establishes a data connection with the FTP server, returning
 * a Socket for the connection if successful.  If a restart
 * offset has been set with {@link #setRestartOffset(long)},
 * a REST command is issued to the server with the offset as
 * an argument before establishing the data connection.  Active
 * mode connections also cause a local PORT command to be issued.
 * <p>/*  ww w  . j a va  2s. co m*/
 * @param command  The text representation of the FTP command to send.
 * @param arg The arguments to the FTP command.  If this parameter is
 *             set to null, then the command is sent with no argument.
 * @return A Socket corresponding to the established data connection.
 *         Null is returned if an FTP protocol error is reported at
 *         any point during the establishment and initialization of
 *         the connection.
 * @exception IOException  If an I/O error occurs while either sending a
 *      command to the server or receiving a reply from the server.
 * @since 3.1
 */
protected Socket _openDataConnection_(String command, String arg) throws IOException {
    if (__dataConnectionMode != ACTIVE_LOCAL_DATA_CONNECTION_MODE
            && __dataConnectionMode != PASSIVE_LOCAL_DATA_CONNECTION_MODE) {
        return null;
    }

    final boolean isInet6Address = getRemoteAddress() instanceof Inet6Address;

    Socket socket;

    if (__dataConnectionMode == ACTIVE_LOCAL_DATA_CONNECTION_MODE) {
        // if no activePortRange was set (correctly) -> getActivePort() = 0
        // -> new ServerSocket(0) -> bind to any free local port
        ServerSocket server = _serverSocketFactory_.createServerSocket(getActivePort(), 1, getHostAddress());

        try {
            // Try EPRT only if remote server is over IPv6, if not use PORT,
            // because EPRT has no advantage over PORT on IPv4.
            // It could even have the disadvantage,
            // that EPRT will make the data connection fail, because
            // today's intelligent NAT Firewalls are able to
            // substitute IP addresses in the PORT command,
            // but might not be able to recognize the EPRT command.
            if (isInet6Address) {
                if (!FTPReply.isPositiveCompletion(eprt(getReportHostAddress(), server.getLocalPort()))) {
                    return null;
                }
            } else {
                if (!FTPReply.isPositiveCompletion(port(getReportHostAddress(), server.getLocalPort()))) {
                    return null;
                }
            }

            if ((__restartOffset > 0) && !restart(__restartOffset)) {
                return null;
            }

            if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) {
                return null;
            }

            // For now, let's just use the data timeout value for waiting for
            // the data connection.  It may be desirable to let this be a
            // separately configurable value.  In any case, we really want
            // to allow preventing the accept from blocking indefinitely.
            if (__dataTimeout >= 0) {
                server.setSoTimeout(__dataTimeout);
            }
            socket = server.accept();

            // Ensure the timeout is set before any commands are issued on the new socket
            if (__dataTimeout >= 0) {
                socket.setSoTimeout(__dataTimeout);
            }
            if (__receiveDataSocketBufferSize > 0) {
                socket.setReceiveBufferSize(__receiveDataSocketBufferSize);
            }
            if (__sendDataSocketBufferSize > 0) {
                socket.setSendBufferSize(__sendDataSocketBufferSize);
            }
        } finally {
            server.close();
        }
    } else { // We must be in PASSIVE_LOCAL_DATA_CONNECTION_MODE

        // Try EPSV command first on IPv6 - and IPv4 if enabled.
        // When using IPv4 with NAT it has the advantage
        // to work with more rare configurations.
        // E.g. if FTP server has a static PASV address (external network)
        // and the client is coming from another internal network.
        // In that case the data connection after PASV command would fail,
        // while EPSV would make the client succeed by taking just the port.
        boolean attemptEPSV = isUseEPSVwithIPv4() || isInet6Address;
        if (attemptEPSV && epsv() == FTPReply.ENTERING_EPSV_MODE) {
            _parseExtendedPassiveModeReply(_replyLines.get(0));
        } else {
            if (isInet6Address) {
                return null; // Must use EPSV for IPV6
            }
            // If EPSV failed on IPV4, revert to PASV
            if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) {
                return null;
            }
            _parsePassiveModeReply(_replyLines.get(0));
        }

        socket = _socketFactory_.createSocket();
        if (__receiveDataSocketBufferSize > 0) {
            socket.setReceiveBufferSize(__receiveDataSocketBufferSize);
        }
        if (__sendDataSocketBufferSize > 0) {
            socket.setSendBufferSize(__sendDataSocketBufferSize);
        }
        if (__passiveLocalHost != null) {
            socket.bind(new InetSocketAddress(__passiveLocalHost, 0));
        }

        // For now, let's just use the data timeout value for waiting for
        // the data connection.  It may be desirable to let this be a
        // separately configurable value.  In any case, we really want
        // to allow preventing the accept from blocking indefinitely.
        if (__dataTimeout >= 0) {
            socket.setSoTimeout(__dataTimeout);
        }

        socket.connect(new InetSocketAddress(__passiveHost, __passivePort), connectTimeout);
        if ((__restartOffset > 0) && !restart(__restartOffset)) {
            socket.close();
            return null;
        }

        if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) {
            socket.close();
            return null;
        }
    }

    if (__remoteVerificationEnabled && !verifyRemote(socket)) {
        socket.close();

        throw new IOException("Host attempting data connection " + socket.getInetAddress().getHostAddress()
                + " is not same as server " + getRemoteAddress().getHostAddress());
    }

    return socket;
}

From source file:open.hyperion.nimblestorage.connection.NonValidatingSocketFactory.java

@Override
public Socket createSocket(String s, int i, InetAddress inetAddress, int i1,
        HttpConnectionParams httpConnectionParams)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    int timeout = httpConnectionParams.getConnectionTimeout();
    Socket socket = _sslContext.getSocketFactory().createSocket();
    SocketAddress localaddr = new InetSocketAddress(inetAddress, i1);
    SocketAddress remoteaddr = new InetSocketAddress(s, i);
    socket.bind(localaddr);
    socket.connect(remoteaddr, timeout);
    return socket;
}

From source file:org.apache.activemq.leveldb.test.MasterLevelDBStoreTest.java

@Test(timeout = 1000 * 60 * 10)
public void testStoppingStoreStopsTransport() throws Exception {
    store = new MasterLevelDBStore();
    store.setReplicas(0);//from www. j ava  2 s . c  o m

    ExecutorService threads = Executors.newFixedThreadPool(1);
    threads.execute(new Runnable() {
        @Override
        public void run() {
            try {
                store.start();
            } catch (Exception e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }
    });

    // give some time to come up..
    Thread.sleep(2000);
    String address = store.transport_server().getBoundAddress();
    URI bindAddress = new URI(address);
    System.out.println(address);
    Socket socket = new Socket();
    try {
        socket.bind(new InetSocketAddress(bindAddress.getHost(), bindAddress.getPort()));
        fail("We should not have been able to connect...");
    } catch (BindException e) {
        System.out.println("Good. We cannot bind.");
    }

    threads.execute(new Runnable() {
        @Override
        public void run() {
            try {
                store.stop();
            } catch (Exception e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }
    });

    Thread.sleep(2000);
    try {
        socket.bind(new InetSocketAddress(bindAddress.getHost(), bindAddress.getPort()));
        System.out.println("Can bind, so protocol server must have been shut down.");

    } catch (IllegalStateException e) {
        fail("Server protocol port is still opened..");
    }

}

From source file:org.apache.axis2.java.security.SSLProtocolSocketFactory.java

public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params) throws IOException {
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }/*from w  w  w .j a va2s.co m*/
    int timeout = params.getConnectionTimeout();
    SocketFactory socketfactory = ctx.getSocketFactory();
    if (timeout == 0) {
        return socketfactory.createSocket(host, port, localAddress, localPort);
    } else {
        Socket socket = socketfactory.createSocket();
        SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
        return socket;
    }
}

From source file:org.apache.flink.runtime.taskmanager.TaskManager.java

private static boolean tryToConnect(InetAddress fromAddress, SocketAddress toSocket, int timeout)
        throws IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Trying to connect to JobManager (" + toSocket + ") from local address " + fromAddress
                + " with timeout " + timeout);
    }/* w w  w  . j  a v  a2s.  c o m*/
    boolean connectable = true;
    Socket socket = null;
    try {
        socket = new Socket();
        SocketAddress bindP = new InetSocketAddress(fromAddress, 0); // 0 = let the OS choose the port on this
        // machine
        socket.bind(bindP);
        socket.connect(toSocket, timeout);
    } catch (Exception ex) {
        LOG.info("Failed to connect to JobManager from address '" + fromAddress + "': " + ex.getMessage());
        if (LOG.isDebugEnabled()) {
            LOG.debug("Failed with exception", ex);
        }
        connectable = false;
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
    return connectable;
}

From source file:org.apache.hadoop.net.HopsSSLSocketFactory.java

@Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort)
        throws IOException, UnknownHostException {
    Socket socket = createSocket();
    socket.bind(new InetSocketAddress(localAddress, localPort));
    socket.connect(new InetSocketAddress(host, port));
    return socket;
}

From source file:org.apache.hadoop.net.HopsSSLSocketFactory.java

@Override
public Socket createSocket(InetAddress inetAddress, int port, InetAddress localAddress, int localPort)
        throws IOException {
    Socket socket = createSocket();
    socket.bind(new InetSocketAddress(localAddress, localPort));
    socket.connect(new InetSocketAddress(inetAddress, port));
    return socket;
}