Java Code Examples for java.net.Socket.bind()

The following are Jave code examples for showing how to use bind() of the java.net.Socket class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: lib-commons-httpclient   File: AuthSSLProtocolSocketFactory.java   Source Code and License Vote up 7 votes
/**
 * Attempts to get a new socket connection to the given host within the given time limit.
 * <p>
 * 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 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();
    SocketFactory socketfactory = getSSLContext().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;
    }
}
 
Example 2
Project: hadoop   File: TestNetUtils.java   Source Code and License Vote up 6 votes
/**
 * Test that we can't accidentally connect back to the connecting socket due
 * to a quirk in the TCP spec.
 *
 * This is a regression test for HADOOP-6722.
 */
@Test
public void testAvoidLoopbackTcpSockets() throws Exception {
  Configuration conf = new Configuration();

  Socket socket = NetUtils.getDefaultSocketFactory(conf)
    .createSocket();
  socket.bind(new InetSocketAddress("127.0.0.1", 0));
  System.err.println("local address: " + socket.getLocalAddress());
  System.err.println("local port: " + socket.getLocalPort());
  try {
    NetUtils.connect(socket,
      new InetSocketAddress(socket.getLocalAddress(), socket.getLocalPort()),
      20000);
    socket.close();
    fail("Should not have connected");
  } catch (ConnectException ce) {
    System.err.println("Got exception: " + ce);
    assertTrue(ce.getMessage().contains("resulted in a loopback"));
  } catch (SocketException se) {
    // Some TCP stacks will actually throw their own Invalid argument exception
    // here. This is also OK.
    assertTrue(se.getMessage().contains("Invalid argument"));
  }
}
 
Example 3
Project: hadoop-oss   File: TestNetUtils.java   Source Code and License Vote up 6 votes
/**
 * Test that we can't accidentally connect back to the connecting socket due
 * to a quirk in the TCP spec.
 *
 * This is a regression test for HADOOP-6722.
 */
@Test
public void testAvoidLoopbackTcpSockets() throws Exception {
  Configuration conf = new Configuration();

  Socket socket = NetUtils.getDefaultSocketFactory(conf)
    .createSocket();
  socket.bind(new InetSocketAddress("127.0.0.1", 0));
  System.err.println("local address: " + socket.getLocalAddress());
  System.err.println("local port: " + socket.getLocalPort());
  try {
    NetUtils.connect(socket,
      new InetSocketAddress(socket.getLocalAddress(), socket.getLocalPort()),
      20000);
    socket.close();
    fail("Should not have connected");
  } catch (ConnectException ce) {
    System.err.println("Got exception: " + ce);
    assertTrue(ce.getMessage().contains("resulted in a loopback"));
  } catch (SocketException se) {
    // Some TCP stacks will actually throw their own Invalid argument exception
    // here. This is also OK.
    assertTrue(se.getMessage().contains("Invalid argument"));
  }
}
 
Example 4
Project: lib-commons-httpclient   File: EasySSLProtocolSocketFactory.java   Source Code and License Vote up 6 votes
/**
 * Attempts to get a new socket connection to the given host within the given time limit.
 * <p>
 * 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 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();
    SocketFactory socketfactory = getSSLContext().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;
    }
}
 
Example 5
Project: Gospy   File: HttpFetcher.java   Source Code and License Vote up 6 votes
@Override
public Socket connectSocket(
        final int connectTimeout,
        final Socket socket, final HttpHost host,
        final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress,
        final HttpContext context
) throws IOException {
    Socket socket0 = socket != null ? socket : createSocket(context);
    if (localAddress != null) {
        socket0.bind(localAddress);
    }
    try {
        socket0.connect(remoteAddress, connectTimeout);
    } catch (SocketTimeoutException e) {
        throw new ConnectTimeoutException(e, host, remoteAddress.getAddress());
    }
    return socket0;
}
 
Example 6
Project: Equella   File: EasySSLProtocolSocketFactory.java   Source Code and License Vote up 6 votes
/**
 * Attempts to get a new socket connection to the given host within the
 * given time limit.
 * <p>
 * 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 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
 */
@Override
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 )
	{
		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;
	}
}
 
Example 7
Project: lib-commons-httpclient   File: SocketFactoryWrapper.java   Source Code and License Vote up 6 votes
public Socket createSocket(
        String host, 
        int port, InetAddress localAddress, int localPort,
        HttpConnectionParams params) throws IOException, UnknownHostException,
        ConnectTimeoutException {
    // Based on code from EasySSLProtocolSocketFactory.java
    Socket rval;
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    int timeout = params.getConnectionTimeout();
    if (timeout == 0) {
        rval = socketFactory.createSocket(host, port, localAddress, localPort);
    } else {
        rval = socketFactory.createSocket();
        SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);
        rval.bind(localaddr);
        rval.connect(remoteaddr, timeout);
    }
    return rval;
}
 
Example 8
Project: TK_1701   File: ClientSocketHandler.java   Source Code and License Vote up 5 votes
@Override
public void run() {
    Log.d(TAG,"run");
    Socket socket = new Socket();
    try {
        /*
        note: setReuseAddress
        When closing a TCP connection, the connection may stay in a time-out state (usually
        referred to as TIME_WAIT state or 2 MSL wait state) for a period of time after the
        close of the connection. For applications that use the well-known socket address or port,
        sockets associated with a socket address or port may be unable to bind to the required
        SocketAddress if it is in the timeout state.
         */
        InetSocketAddress addr = new InetSocketAddress(mAddress.getHostAddress(),WiFiDirectCommunicator.PORT);
        socket.bind(null);
        socket.setReuseAddress(true);
        socket.connect(addr,WiFiDirectCommunicator.TIMEOUT);
        Log.d(TAG, "Launching the I/O handler");
        manager = new CommManager(socket, handler);
        new Thread(manager).start();
    } catch (IOException e) {
        e.printStackTrace();
        try {
            socket.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return;
    }
}
 
Example 9
Project: hadoop-oss   File: StandardSocketFactory.java   Source Code and License Vote up 5 votes
@Override
public Socket createSocket(InetAddress addr, int port,
    InetAddress localHostAddr, int localPort) throws IOException {

  Socket socket = createSocket();
  socket.bind(new InetSocketAddress(localHostAddr, localPort));
  socket.connect(new InetSocketAddress(addr, port));
  return socket;
}
 
Example 10
Project: hadoop-oss   File: SocksSocketFactory.java   Source Code and License Vote up 5 votes
@Override
public Socket createSocket(InetAddress addr, int port,
    InetAddress localHostAddr, int localPort) throws IOException {

  Socket socket = createSocket();
  socket.bind(new InetSocketAddress(localHostAddr, localPort));
  socket.connect(new InetSocketAddress(addr, port));
  return socket;
}
 
Example 11
Project: aos-FileCoreLibrary   File: DefaultSocketFactory.java   Source Code and License Vote up 5 votes
/***
 * Creates a Socket connected to the given host and port and
 * originating from the specified local address and port.
 * <p>
 * @param address The address of the host to connect to.
 * @param port The port to connect to.
 * @param localAddr  The local address to use.
 * @param localPort  The local port to use.
 * @return A Socket connected to the given host and port.
 * @exception java.io.IOException If an I/O error occurs while creating the Socket.
 ***/
@Override
public Socket createSocket(InetAddress address, int port,
                           InetAddress localAddr, int localPort)
throws IOException
{
    if (connProxy != null)
    {
        Socket s = new Socket(connProxy);
        s.bind(new InetSocketAddress(localAddr, localPort));
        s.connect(new InetSocketAddress(address, port));
        return s;
    }
    return new Socket(address, port, localAddr, localPort);
}
 
Example 12
Project: nifi-tools   File: SocksProxySocketFactory.java   Source Code and License Vote up 5 votes
@Override
public Socket createSocket(String host, int port, InetAddress localHostAddr, int localPort) throws IOException, UnknownHostException {
    Socket socket = createSocket();
    socket.bind(new InetSocketAddress(localHostAddr, localPort));
    socket.connect(new InetSocketAddress(host, port));
    return socket;
}
 
Example 13
Project: hadoop   File: SocksSocketFactory.java   Source Code and License Vote up 5 votes
@Override
public Socket createSocket(InetAddress addr, int port,
    InetAddress localHostAddr, int localPort) throws IOException {

  Socket socket = createSocket();
  socket.bind(new InetSocketAddress(localHostAddr, localPort));
  socket.connect(new InetSocketAddress(addr, port));
  return socket;
}
 
Example 14
Project: FirefoxData-android   File: PlainSocketFactory.java   Source Code and License Vote up 5 votes
/**
 * @since 4.1
 */
public Socket connectSocket(
        final Socket socket,
        final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress,
        final HttpParams params) throws IOException, ConnectTimeoutException {
    Args.notNull(remoteAddress, "Remote address");
    Args.notNull(params, "HTTP parameters");
    Socket sock = socket;
    if (sock == null) {
        sock = createSocket();
    }
    if (localAddress != null) {
        sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        sock.bind(localAddress);
    }
    final int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    final int soTimeout = HttpConnectionParams.getSoTimeout(params);

    try {
        sock.setSoTimeout(soTimeout);
        sock.connect(remoteAddress, connTimeout);
    } catch (final SocketTimeoutException ex) {
        throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out");
    }
    return sock;
}
 
Example 15
Project: xdman   File: DefaultSocketFactory.java   Source Code and License Vote up 5 votes
/***
 * Creates a Socket connected to the given host and port and
 * originating from the specified local address and port.
 * <p>
 * @param host The hostname to connect to.
 * @param port The port to connect to.
 * @param localAddr  The local address to use.
 * @param localPort  The local port to use.
 * @return A Socket connected to the given host and port.
 * @exception UnknownHostException  If the hostname cannot be resolved.
 * @exception IOException If an I/O error occurs while creating the Socket.
 ***/
@Override
public Socket createSocket(String host, int port,
                           InetAddress localAddr, int localPort)
throws UnknownHostException, IOException
{
    if (connProxy != null)
    {
        Socket s = new Socket(connProxy);
        s.bind(new InetSocketAddress(localAddr, localPort));
        s.connect(new InetSocketAddress(host, port));
        return s;
    }
    return new Socket(host, port, localAddr, localPort);
}
 
Example 16
Project: FirefoxData-android   File: SSLSocketFactory.java   Source Code and License Vote up 5 votes
public Socket connectSocket(
        final int connectTimeout,
        final Socket socket,
        final HttpHost host,
        final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress,
        final HttpContext context) throws IOException {
    Args.notNull(host, "HTTP host");
    Args.notNull(remoteAddress, "Remote address");
    final Socket sock = socket != null ? socket : createSocket(context);
    if (localAddress != null) {
        sock.bind(localAddress);
    }
    try {
        sock.connect(remoteAddress, connectTimeout);
    } catch (final IOException ex) {
        try {
            sock.close();
        } catch (final IOException ignore) {
        }
        throw ex;
    }
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        final SSLSocket sslsock = (SSLSocket) sock;
        sslsock.startHandshake();
        verifyHostname(sslsock, host.getHostName());
        return sock;
    } else {
        return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
    }
}
 
Example 17
Project: spark_deep   File: StandardSocketFactory.java   Source Code and License Vote up 5 votes
@Override
public Socket createSocket(InetAddress addr, int port,
    InetAddress localHostAddr, int localPort) throws IOException {

  Socket socket = createSocket();
  socket.bind(new InetSocketAddress(localHostAddr, localPort));
  socket.connect(new InetSocketAddress(addr, port));
  return socket;
}
 
Example 18
Project: Java_Certificado   File: SocketFactoryDinamico.java   Source Code and License Vote up 5 votes
@Override
public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException {
    final Socket socket = this.ssl.getSocketFactory().createSocket();
    socket.bind(new InetSocketAddress(localAddress, localPort));
    socket.connect(new InetSocketAddress(host, port), 60000);
    return socket;
}
 
Example 19
Project: FlashLib   File: TCPCommInterface.java   Source Code and License Vote up 4 votes
private void createSocket() throws IOException{
	socket = new Socket();
	socket.bind(new InetSocketAddress(localInet, localPort));
}
 
Example 20
Project: hadoop   File: NetUtils.java   Source Code and License Vote up 4 votes
/**
 * Like {@link NetUtils#connect(Socket, SocketAddress, int)} but
 * also takes a local address and port to bind the socket to. 
 * 
 * @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.");
  }
}