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:cc.abstra.trantor.security.ssl.OwnSSLProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the given time limit.
 * <p>/*from  ww  w .ja  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();
    Socket socket = null;

    SocketFactory socketfactory = getSSLContext().getSocketFactory();
    if (timeout == 0) {
        socket = socketfactory.createSocket(host, port, localAddress, localPort);
    } else {
        socket = socketfactory.createSocket();
        SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
    }
    verifyHostname((SSLSocket) socket);
    return socket;
}

From source file:gov.miamidade.open311.utilities.SslContextedSecureProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the
 * given time limit.//from ww w .  j  av a 2s. co  m
 * <p>
 * This method employs several techniques to circumvent the limitations of
 * older JREs that do not support connect timeout. When running in JRE 1.4
 * or above reflection is used to call Socket#connect(SocketAddress
 * endpoint, int timeout) method. When executing in older JREs 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 clientHost
 *            the local host name/IP to bind the socket to
 * @param clientPort
 *            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();
    Socket socket = null;

    SocketFactory socketfactory = getSslSocketFactory();
    if (timeout == 0) {
        socket = socketfactory.createSocket(host, port, localAddress, localPort);
    } else {
        socket = socketfactory.createSocket();
        SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
    }
    verifyHostname((SSLSocket) socket);
    return socket;
}

From source file:org.eclipse.ecf.internal.provider.filetransfer.httpclient4.ECFHttpClientProtocolSocketFactory.java

public Socket connectSocket(final Socket sock, InetSocketAddress remoteAddress, InetSocketAddress localAddress,
        HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    int timeout = params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0);

    Trace.entering(Activator.PLUGIN_ID, DebugOptions.METHODS_ENTERING, ECFHttpClientProtocolSocketFactory.class,
            "connectSocket " + remoteAddress.toString() + " timeout=" + timeout); //$NON-NLS-1$ //$NON-NLS-2$

    try {//from www .  j  a v  a2 s.co m
        // Use String.valueOf to protect against null
        Trace.trace(Activator.PLUGIN_ID, "bind(" + String.valueOf(localAddress) + ")"); //$NON-NLS-1$//$NON-NLS-2$
        sock.bind(localAddress);
        Trace.trace(Activator.PLUGIN_ID, "connect(" + remoteAddress.toString() + ", " + timeout + ")"); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
        sock.connect(remoteAddress, timeout);
        Trace.trace(Activator.PLUGIN_ID, "connected"); //$NON-NLS-1$
    } catch (IOException e) {
        Trace.catching(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_CATCHING,
                ECFHttpClientProtocolSocketFactory.class, "createSocket", e); //$NON-NLS-1$
        fireEvent(socketConnectListener, new SocketClosedEvent(source, sock, sock));
        Trace.throwing(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_THROWING,
                ECFHttpClientProtocolSocketFactory.class, "createSocket", e); //$NON-NLS-1$
        throw e;
    }

    Socket toReturn;
    Socket wrapped = new CloseMonitoringSocket(sock, socketConnectListener, source);

    SocketConnectedEvent connectedEvent = new SocketConnectedEvent(source, sock, wrapped);
    fireEvent(socketConnectListener, connectedEvent);

    // Change the wrapped socket if one of the receivers of the SocketConnectedEvent changed it
    if (connectedEvent.getSocket() != wrapped) {
        toReturn = connectedEvent.getSocket();
        ((CloseMonitoringSocket) wrapped).setWrappedSocket(toReturn);
    } else {
        toReturn = wrapped;
    }

    return toReturn;
}

From source file:info.guardianproject.net.SocksSocketFactory.java

@Override
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort,
        HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {

    if (host == null) {
        throw new IllegalArgumentException("Target host may not be null.");
    }//  ww w  .j  ava  2  s . c o  m
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null.");
    }

    if (sock == null)
        sock = createSocket();

    if ((localAddress != null) || (localPort > 0)) {

        // we need to bind explicitly
        if (localPort < 0)
            localPort = 0; // indicates "any"

        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sock.bind(isa);
    }

    return new SocksSocket(sProxy, host, port);

}

From source file:org.apache.chemistry.opencmis.client.bindings.spi.http.ApacheClientHttpInvoker.java

/**
 * Builds a SSL Socket Factory for the Apache HTTP Client.
 *///  w w  w .  ja v a  2s .  c  o m
private SchemeLayeredSocketFactory getSSLSocketFactory(final UrlBuilder url, final BindingSession session) {
    // get authentication provider
    AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session);

    // check SSL Socket Factory
    final SSLSocketFactory sf = authProvider.getSSLSocketFactory();
    if (sf == null) {
        // no custom factory -> return default factory
        return org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory();
    }

    // check hostame verifier and use default if not set
    final HostnameVerifier hv = (authProvider.getHostnameVerifier() == null
            ? new BrowserCompatHostnameVerifier()
            : authProvider.getHostnameVerifier());

    if (hv instanceof X509HostnameVerifier) {
        return new org.apache.http.conn.ssl.SSLSocketFactory(sf, (X509HostnameVerifier) hv);
    }

    // build new socket factory
    return new SchemeLayeredSocketFactory() {

        @Override
        public boolean isSecure(Socket sock) {
            return true;
        }

        @Override
        public Socket createSocket(HttpParams params) throws IOException {
            return sf.createSocket();
        }

        @Override
        public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress,
                final InetSocketAddress localAddress, final HttpParams params) throws IOException {

            Socket sock = socket != null ? socket : createSocket(params);
            if (localAddress != null) {
                sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
                sock.bind(localAddress);
            }

            int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
            int soTimeout = HttpConnectionParams.getSoTimeout(params);

            try {
                sock.setSoTimeout(soTimeout);
                sock.connect(remoteAddress, connTimeout);
            } catch (SocketTimeoutException ex) {
                closeSocket(sock);
                throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out!");
            }

            String host;
            if (remoteAddress instanceof HttpInetSocketAddress) {
                host = ((HttpInetSocketAddress) remoteAddress).getHttpHost().getHostName();
            } else {
                host = remoteAddress.getHostName();
            }

            SSLSocket sslSocket;
            if (sock instanceof SSLSocket) {
                sslSocket = (SSLSocket) sock;
            } else {
                int port = remoteAddress.getPort();
                sslSocket = (SSLSocket) sf.createSocket(sock, host, port, true);
            }
            verify(hv, host, sslSocket);

            return sslSocket;
        }

        @Override
        public Socket createLayeredSocket(final Socket socket, final String host, final int port,
                final HttpParams params) throws IOException {
            SSLSocket sslSocket = (SSLSocket) sf.createSocket(socket, host, port, true);
            verify(hv, host, sslSocket);

            return sslSocket;
        }
    };
}

From source file:org.openqa.selenium.remote.ReusingSocketSocketFactory.java

public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort,
        HttpParams params) throws IOException {

    if (host == null) {
        throw new IllegalArgumentException("Target host may not be null.");
    }/*from  w  w w  .j  av  a  2s  .  com*/
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null.");
    }

    if (sock == null)
        sock = createSocket();

    sock.setReuseAddress(true); // This is the 1 line added by kristian
    if ((localAddress != null) || (localPort > 0)) {

        // we need to bind explicitly
        if (localPort < 0)
            localPort = 0; // indicates "any"

        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sock.bind(isa);
    }

    int timeout = HttpConnectionParams.getConnectionTimeout(params);

    InetSocketAddress remoteAddress;
    if (this.nameResolver != null) {
        remoteAddress = new InetSocketAddress(this.nameResolver.resolve(host), port);
    } else {
        remoteAddress = new InetSocketAddress(host, port);
    }
    try {
        sock.connect(remoteAddress, timeout);
    } catch (SocketTimeoutException ex) {
        throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out");
    }
    return sock;
}

From source file:orca.ektorp.client.ContextualSSLSocketFactory.java

/**
 * @since 4.1//from w  w w .  j a  va  2s. c  om
 * @param socket socket
 * @param remoteAddress remote address
 * @param localAddress local address
 * @param params HTTP params
 * @throws IOException in case of IO error
 * @throws UnknownHostException in case of unknonwn host
 * @throws ConnectTimeoutException in case of connect timeout
 * @return returns the socket
 */
public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress, final HttpParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (remoteAddress == null) {
        throw new IllegalArgumentException("Remote address may not be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    //Here!
    Socket sock = socket != null ? socket : this.socketfactory.createSocket();
    if (localAddress != null) {
        sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        sock.bind(localAddress);
    }

    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);

    try {
        sock.setSoTimeout(soTimeout);
        sock.connect(remoteAddress, connTimeout);
    } catch (SocketTimeoutException ex) {
        throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out");
    }

    String hostname;
    if (remoteAddress instanceof HttpInetSocketAddress) {
        hostname = ((HttpInetSocketAddress) remoteAddress).getHttpHost().getHostName();
    } else {
        hostname = remoteAddress.getHostName();
    }

    SSLSocket sslsock;
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        sslsock = (SSLSocket) sock;
    } else {
        int port = remoteAddress.getPort();
        sslsock = (SSLSocket) this.socketfactory.createSocket(sock, hostname, port, true);
        prepareSocket(sslsock);
    }
    if (this.hostnameVerifier != null) {
        try {
            this.hostnameVerifier.verify(hostname, sslsock);
            // verifyHostName() didn't blowup - good!
        } catch (IOException iox) {
            // close the socket before re-throwing the exception
            try {
                sslsock.close();
            } catch (Exception x) {
                /*ignore*/ }
            throw iox;
        }
    }
    return sslsock;
}

From source file:com.groupon.odo.bmp.http.SimulatedSocketFactory.java

@Override
public Socket connectSocket(Socket sock, InetSocketAddress remoteAddress, InetSocketAddress localAddress,
        HttpParams params) throws IOException {
    if (remoteAddress == null) {
        throw new IllegalArgumentException("Target host may not be null.");
    }//www . j  a va 2 s  . c o  m

    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null.");
    }

    if (sock == null) {
        sock = createSocket(null);
    }

    if ((localAddress != null)) {
        sock.bind(localAddress);
    }

    String hostName;
    if (remoteAddress instanceof HttpInetSocketAddress) {
        hostName = ((HttpInetSocketAddress) remoteAddress).getHttpHost().getHostName();
    } else {
        hostName = resolveHostName(remoteAddress);
    }

    InetSocketAddress remoteAddr = remoteAddress;
    // BEGIN ODO CHANGES
    if (this.hostNameResolver != null) {
        // send request to Odo HTTP port
        int port = Utils.getSystemPort(Constants.SYS_HTTP_PORT);
        remoteAddr = new InetSocketAddress(this.hostNameResolver.resolve(hostName), port);
    }
    // END ODO CHANGES

    int timeout = HttpConnectionParams.getConnectionTimeout(params);

    try {
        sock.connect(remoteAddr, timeout);
    } catch (SocketTimeoutException ex) {
        throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out");
    }

    return sock;
}

From source file:com.cyberway.issue.crawler.fetcher.HeritrixSSLProtocolSocketFactory.java

public synchronized Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
        HttpConnectionParams params) throws IOException, UnknownHostException {
    // Below code is from the DefaultSSLProtocolSocketFactory#createSocket
    // method only it has workarounds to deal with pre-1.4 JVMs.  I've
    // cut these out.
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }//from ww w  .j a va2s.  c  o  m
    Socket socket = null;
    int timeout = params.getConnectionTimeout();
    if (timeout == 0) {
        socket = createSocket(host, port, localAddress, localPort);
    } else {
        SSLSocketFactory factory = (SSLSocketFactory) params.getParameter(FetchHTTP.SSL_FACTORY_KEY);
        SSLSocketFactory f = (factory != null) ? factory : this.sslDefaultFactory;
        socket = f.createSocket();
        ServerCache cache = (ServerCache) params.getParameter(FetchHTTP.SERVER_CACHE_KEY);
        InetAddress hostAddress = (cache != null) ? HeritrixProtocolSocketFactory.getHostAddress(cache, host)
                : null;
        InetSocketAddress address = (hostAddress != null) ? new InetSocketAddress(hostAddress, port)
                : new InetSocketAddress(host, port);
        socket.bind(new InetSocketAddress(localAddress, localPort));
        try {
            socket.connect(address, timeout);
        } catch (SocketTimeoutException e) {
            // Add timeout info. to the exception.
            throw new SocketTimeoutException(
                    e.getMessage() + ": timeout set at " + Integer.toString(timeout) + "ms.");
        }
        assert socket.isConnected() : "Socket not connected " + host;
    }
    return socket;
}

From source file:io.hops.hopsworks.api.util.CustomSSLProtocolSocketFactory.java

@Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
        HttpConnectionParams httpConnectionParams)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (httpConnectionParams == null) {
        LOG.log(Level.SEVERE, "Creating SSL socket but HTTP connection parameters is null");
        throw new IllegalArgumentException("HTTP connection parameters cannot be null");
    }//from   w  ww .j av  a  2s.  c  o m

    Socket socket = getSslContext().getSocketFactory().createSocket();
    SocketAddress localSocketAddress = new InetSocketAddress(localAddress, localPort);
    SocketAddress remoteSocketAddress = new InetSocketAddress(host, port);

    socket.setSoTimeout(httpConnectionParams.getSoTimeout());
    if (httpConnectionParams.getLinger() > 0) {
        socket.setSoLinger(true, httpConnectionParams.getLinger());
    } else {
        socket.setSoLinger(false, 0);
    }
    socket.setTcpNoDelay(httpConnectionParams.getTcpNoDelay());
    if (httpConnectionParams.getSendBufferSize() >= 0) {
        socket.setSendBufferSize(httpConnectionParams.getSendBufferSize());
    }
    if (httpConnectionParams.getReceiveBufferSize() >= 0) {
        socket.setReceiveBufferSize(httpConnectionParams.getReceiveBufferSize());
    }

    socket.bind(localSocketAddress);
    socket.connect(remoteSocketAddress, httpConnectionParams.getConnectionTimeout());
    return socket;
}