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

The following examples show how to use java.net.Socket#bind() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClientSocketHandler.java    From WiFi-Buddy with MIT License 6 votes vote down vote up
@Override
public void run() {
    Log.i(TAG, "Client socket thread running");
    Socket socket = new Socket();
    try {
        Log.i(TAG, "Opening client socket");
        socket.bind(null);
        socket.connect(new InetSocketAddress(inetAddress.getHostAddress(),
                WifiDirectHandler.SERVER_PORT), SOCKET_TIMEOUT);
        Log.i(TAG, "Client socket - " + socket.isConnected());

        Log.i(TAG, "Launching the I/O handler");
        CommunicationManager communicationManager = new CommunicationManager(socket, handler);
        new Thread(communicationManager).start();
    } catch (IOException e) {
        Log.e(TAG, "Error launching I/O handler");
        Log.e(TAG, e.getMessage());
        try {
            socket.close();
            Log.i(TAG, "Client socket closed");
        } catch (IOException e1) {
            Log.e(TAG, "Error closing client socket");
            e1.printStackTrace();
        }
    }
}
 
Example 2
Source File: Utilities.java    From XLearning with Apache License 2.0 6 votes vote down vote up
public static void getReservePort(Socket socket, String localHost, int reservePortBegin, int reservePortEnd) throws IOException {
  int i = 0;
  Random random = new Random(System.currentTimeMillis());
  while (i < 1000) {
    int rand = random.nextInt(reservePortEnd - reservePortBegin);
    try {
      socket.bind(new InetSocketAddress(localHost, reservePortBegin + rand));
      return;
    } catch (IOException e) {
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e2) {}
    }
  }
  throw new IOException("couldn't allocate a unused port");
}
 
Example 3
Source File: HttpsUtils.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host,
		final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context)
		throws IOException, ConnectTimeoutException {
	Socket sock;
	if (socket != null) {
		sock = socket;
	} else {
		sock = createSocket(context);
	}
	if (localAddress != null) {
		sock.bind(localAddress);
	}
	try {
		sock.connect(remoteAddress, connectTimeout);
	} catch (SocketTimeoutException ex) {
		throw new ConnectTimeoutException(ex, host, remoteAddress.getAddress());
	}
	return sock;
}
 
Example 4
Source File: SocketTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testFileDescriptorStaysSame() throws Exception {
    // SocketImplementation FileDescriptor object shouldn't change after calling
    // bind (and many other methods).
    Socket s = new Socket();

    // There's an assumption that newly created
    // socket has a non-null file-descriptor (b/26169052, b/26084000)
    FileDescriptor fd1 = s.getFileDescriptor$();
    assertNotNull(fd1);
    int fd1Val = fd1.getInt$();
    assertEquals(-1, fd1Val);

    s.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0));
    FileDescriptor fd2 = s.getFileDescriptor$();
    assertSame(fd1, fd2);
    int fd2Val = fd2.getInt$();
    assertTrue(fd1Val != fd2Val); // The actual fd should be different

    s.close();
    FileDescriptor fd3 = s.getFileDescriptor$();
    assertSame(fd1, fd3);
    assertFalse(fd3.valid());
}
 
Example 5
Source File: SimpleSSLProtocolSocketFactory.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 HttpParams params
) throws IOException, UnknownHostException, ConnectTimeoutException {
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    int timeout = HttpConnectionParams.getConnectionTimeout(params);
    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 6
Source File: SocketChannelTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private void assertSocketAction_Block_BeforeConnect(Socket s)
        throws IOException {
    assertFalse(this.channel1.isConnected());
    s.connect(localAddr2);
    assertTrue(this.channel1.isConnected());
    assertTrue(s.isConnected());

    assertSocketAfterConnect(s, localAddr2);

    try {
        s.bind(localAddr2);
        fail("Should throw SocketException");
    } catch (SocketException e) {
        // OK.
    }

    s.close();
    assertTrue(s.isClosed());
    assertFalse(this.channel1.isOpen());
}
 
Example 7
Source File: TestNetUtils.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * 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 8
Source File: BulkLoadConnectionFactory.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
public Socket createConnection(InetAddress peer) throws IOException
{
    // Connect to secure port for all peers if ServerEncryptionOptions is configured other than 'none'
    // When 'all', 'dc' and 'rack', server nodes always have SSL port open, and since thin client like sstableloader
    // does not know which node is in which dc/rack, connecting to SSL port is always the option.
    if (encryptionOptions != null && encryptionOptions.internode_encryption != EncryptionOptions.ServerEncryptionOptions.InternodeEncryption.none)
    {
        if (outboundBindAny)
            return SSLFactory.getSocket(encryptionOptions, peer, secureStoragePort);
        else
            return SSLFactory.getSocket(encryptionOptions, peer, secureStoragePort, FBUtilities.getLocalAddress(), 0);
    }
    else
    {
        Socket socket = SocketChannel.open(new InetSocketAddress(peer, storagePort)).socket();
        if (outboundBindAny && !socket.isBound())
            socket.bind(new InetSocketAddress(FBUtilities.getLocalAddress(), 0));
        return socket;
    }
}
 
Example 9
Source File: TestNetUtils.java    From RDFS with Apache License 2.0 6 votes vote down vote up
/**
 * 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) {
    System.err.println("Got exception: " + se);
    assertTrue(se.getMessage().startsWith("Invalid argument"));
  }
}
 
Example 10
Source File: OutboundSocketBinding.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Socket createSocket() throws IOException {
    final ManagedSocketFactory socketFactory = this.socketBindingManager.getSocketFactory();
    final Socket socket = socketFactory.createSocket(this.name);
    // if the outbound binding specifies the source to use, then bind this socket to the
    // appropriate source
    final SocketAddress sourceSocketAddress = this.getOptionalSourceSocketAddress();
    if (sourceSocketAddress != null) {
        socket.bind(sourceSocketAddress);
    }
    return socket;
}
 
Example 11
Source File: SocketBindingManagerImpl.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Socket createSocket(final String name, final InetAddress address, final int port, final InetAddress localAddress, final int localPort) throws IOException {
    final Socket socket = createSocket(name);
    socket.bind(new InetSocketAddress(localAddress, localPort));
    socket.connect(new InetSocketAddress(address, port));
    return socket;
}
 
Example 12
Source File: SocksSocketFactory.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@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 13
Source File: WiFiDirectActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 5 votes vote down vote up
private void startWifiDirectClient(String hostAddress) {
  Socket socket = new Socket();
  InetSocketAddress socketAddress = new InetSocketAddress(hostAddress, port);
  try {
    socket.bind(null);
    socket.connect(socketAddress, timeout);
    listenForWiFiMessages(socket);
  } catch (IOException e) {
    Log.e(TAG, "IO Exception.", e);
  }
}
 
Example 14
Source File: GameClient.java    From texaspoker with GNU General Public License v2.0 5 votes vote down vote up
public GameClient(String serverIp, int serverPort, String clientIp, 
        int clientPort, String playerID, boolean needNotify) {
    boolean flag = false;
    while (!flag) {
        try {
            socket = new Socket(); //此时Socket对象未绑定到本地端口,并且未连接远程服务器
            socket.setReuseAddress(true);

            SocketAddress localAddr = new InetSocketAddress(clientIp, clientPort);
            SocketAddress remoteAddr = new InetSocketAddress(serverIp, serverPort);

            socket.bind(localAddr); //与本地端口绑定
            
            socket.connect(remoteAddr, 200);
            flag = true;
            System.out.println("success!");
            input = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
            output = new PrintWriter(socket.getOutputStream(), true);
            
        } catch (Exception e) {
            System.out.println("connect failed,try again!");
            try {
                socket.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
    }
    
    this.playerID = playerID;
    if (needNotify) {
        this.needNotify = "need_notify ";
    }
    else {
        this.needNotify = "";
    }
}
 
Example 15
Source File: CustomLocalServerReceiver.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private static int getUnusedPort() throws IOException {
  Socket s = new Socket();
  s.bind( (SocketAddress) null );

  int var1;
  try {
    var1 = s.getLocalPort();
  } finally {
    s.close();
  }
  return var1;
}
 
Example 16
Source File: SocketFactoryImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public Socket createSocket(String host, int port, InetAddress local,
    int localPort) throws IOException {
  Socket s  = createSocket();
  s.bind(new InetSocketAddress(local, localPort));
  s.connect(new InetSocketAddress(host, port), SO_CONNECT_TIMEOUT);
  return s;
}
 
Example 17
Source File: StrictSSLProtocolSocketFactory.java    From http4e with Apache License 2.0 5 votes vote down vote up
/**
 * Attempts to get a new socket connection to the given host within the given time limit.
 * <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 = SSLSocketFactory.getDefault();
    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;
}
 
Example 18
Source File: StandardSocketFactory.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@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 19
Source File: NetUtils.java    From hadoop with Apache License 2.0 4 votes vote down vote up
/**
 * 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.");
  }
}
 
Example 20
Source File: EasySSLProtocolSocketFactory.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
    }
}