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

The following examples show how to use java.net.Socket#getLocalPort() . 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: SocketTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Our getLocalAddress and getLocalPort currently use getsockname(3).
 * This means they give incorrect results on closed sockets (as well
 * as requiring an unnecessary call into native code).
 */
public void test_getLocalAddress_after_close() throws Exception {
    Socket s = new Socket();
    try {
        // Bind to an ephemeral local port.
        s.bind(new InetSocketAddress("localhost", 0));
        assertTrue(s.getLocalAddress().toString(), s.getLocalAddress().isLoopbackAddress());
        // What local port did we get?
        int localPort = s.getLocalPort();
        assertTrue(localPort > 0);
        // Now close the socket...
        s.close();
        // The RI returns the ANY address but the original local port after close.
        assertTrue(s.getLocalAddress().isAnyLocalAddress());
        assertEquals(localPort, s.getLocalPort());
    } finally {
        s.close();
    }
}
 
Example 2
Source File: SocketFactoryTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void test_createSocket_InetAddressIInetAddressI_ExceptionOrder() throws IOException {
    int invalidPort = Integer.MAX_VALUE;
    SocketFactory sf = SocketFactory.getDefault();
    int validServerPortNumber = new ServerSocket(0).getLocalPort();

    // Create a socket with localhost as the client address so that another attempt to bind
    // would fail.
    Socket s = sf.createSocket(InetAddress.getLocalHost() /* ServerAddress */,
            validServerPortNumber /* ServerPortNumber */,
            InetAddress.getLocalHost() /* ClientAddress */,
            0 /* ClientPortNumber */);

    int assignedLocalPortNumber = s.getLocalPort();

    // Create a socket with an invalid port and localhost as the client address. Both
    // BindException and IllegalArgumentException are expected in this case as the address is
    // already bound to the socket above and port is invalid, however, to preserve the
    // precedence order, IllegalArgumentException should be thrown.
    try (Socket s1 = sf.createSocket(InetAddress.getLocalHost() /* ServerAddress */,
            invalidPort /* ServerPortNumber */,
            InetAddress.getLocalHost() /* ClientAddress */,
            assignedLocalPortNumber /* ClientPortNumber */)) {
        fail("IllegalArgumentException wasn't thrown for " + invalidPort);
    } catch (IllegalArgumentException expected) {
    }
}
 
Example 3
Source File: FrontendConnection.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
public FrontendConnection(SocketChannel channel){
    super(channel);
    Socket socket = channel.socket();
    this.host = socket.getInetAddress().getHostAddress();
    this.port = socket.getPort();
    this.localPort = socket.getLocalPort();
    this.handler = new FrontendAuthenticator(this);
}
 
Example 4
Source File: SocketWrapperBar.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the server port that accepted the request.
 */
@Override
public int portLocal()
{
  Socket s = getSocket();
  
  if (s != null) {
    return s.getLocalPort();
  }
  else {
    return -1;
  }
}
 
Example 5
Source File: RouterStub.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Establishes a connection to the router. The router will send my address (its peer address) back
 * as an Address, which is subsequently returned to the caller. The reason for not using
 * InetAddress.getLocalHost() or sock.getLocalAddress() is that this may not be permitted
 * with certain security managers (e.g if this code runs in an applet). Also, some network
 * address translation (NAT) (e.g IP Masquerading) may return the wrong address.
 */
public synchronized Address connect() throws Exception {
    Address ret=null;
    int len=0;
    byte[] buf;

    try {
        sock=new Socket(router_host, router_port);
        sock.setSoLinger(true, 500);

        // Retrieve our own address by reading it from the socket
        input=new DataInputStream(sock.getInputStream());
        len=input.readInt();
        buf=new byte[len];
        input.readFully(buf);
        ret=(Address)Util.objectFromByteBuffer(buf);
        output=new DataOutputStream(sock.getOutputStream());
        connected=true;
    }
    catch(Exception e) {
        connected=false;
        if(sock != null)
            sock.close();
        throw e;
    }

    // IpAddress uses InetAddress.getLocalHost() to find the host. May not be permitted in applets !
    if(ret == null && sock != null)
        ret=new com.gemstone.org.jgroups.stack.IpAddress(sock.getLocalPort());

    // set local address; this is the one that we will use from now on !
    if(local_addr == null)
        local_addr=ret;

    return ret;
}
 
Example 6
Source File: OkNetworkEventListener.java    From AndroidGodEye with Apache License 2.0 5 votes vote down vote up
@Override
public void connectionAcquired(Call call, Connection connection) {
    super.connectionAcquired(call, connection);
    Handshake handshake = connection.handshake();
    String cipherSuite = "";
    String tlsVersion = "";
    if (handshake != null) {
        cipherSuite = handshake.cipherSuite().javaName();
        tlsVersion = handshake.tlsVersion().javaName();
    }
    Socket socket = connection.socket();
    int localPort = socket.getLocalPort();
    int remotePort = socket.getPort();
    String localIp = "";
    String remoteIp = "";
    InetAddress localAddress = socket.getLocalAddress();
    if (localAddress != null) {
        localIp = localAddress.getHostAddress();
    }
    InetAddress remoteAddress = socket.getInetAddress();
    if (remoteAddress != null) {
        remoteIp = remoteAddress.getHostAddress();
    }
    mNetworkInfo.extraInfo.put("cipherSuite", cipherSuite);
    mNetworkInfo.extraInfo.put("tlsVersion", tlsVersion);
    mNetworkInfo.extraInfo.put("localIp", localIp);
    mNetworkInfo.extraInfo.put("localPort", localPort);
    mNetworkInfo.extraInfo.put("remoteIp", remoteIp);
    mNetworkInfo.extraInfo.put("remotePort", remotePort);
}
 
Example 7
Source File: NetUtils.java    From RDFS with Apache License 2.0 5 votes vote down vote up
public static void connect(Socket socket, 
                           SocketAddress endpoint, 
                           int timeout, 
                           int ipTosValue) throws IOException {
  if (socket == null || endpoint == null || timeout < 0 
  		|| ipTosValue < NOT_SET_IP_TOS 
  		|| ipTosValue > IP_TOS_MAX_VALUE) {
    throw new IllegalArgumentException("Illegal argument for connect()");
  }
  
  SocketChannel ch = socket.getChannel();
  
  if (ch == null) {
    // let the default implementation handle it.
    socket.connect(endpoint, timeout);
  } else {
  	// set the socket IP_TOS value
  	if (ipTosValue != NOT_SET_IP_TOS) {
  		LinuxSystemCall.setIPTOSVal(ch, ipTosValue);
  	}
    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.");
  }
}
 
Example 8
Source File: TestSocketFactory.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Construct a socket that interposes on a socket to match and replace.
 * @param socket the underlying socket
 * @param triggerBytes array of bytes to enable matching
 * @param matchBytes the bytes that must match
 * @param replaceBytes the replacement bytes
 */
public InterposeSocket(Socket socket, byte[]
        triggerBytes, byte[] matchBytes, byte[] replaceBytes) {
    this.socket = socket;
    this.triggerBytes = Objects.requireNonNull(triggerBytes, "triggerBytes");
    this.matchBytes = Objects.requireNonNull(matchBytes, "matchBytes");
    this.replaceBytes = Objects.requireNonNull(replaceBytes, "replaceBytes");
    this.inLogStream = new ByteArrayOutputStream();
    this.outLogStream = new ByteArrayOutputStream();
    this.name = "IS" + ++num + "::"
            + Thread.currentThread().getName() + ": "
            + socket.getLocalPort() + " <  " + socket.getPort();
}
 
Example 9
Source File: SocksSocket.java    From T0rlib4j with Apache License 2.0 5 votes vote down vote up
private void doDirect() throws SocksException {
	try {
		log.debug("IP: {}_{}", remoteIP, remotePort);
		directSock = new Socket(remoteIP, remotePort);
		proxy.out = directSock.getOutputStream();
		proxy.in = directSock.getInputStream();
		proxy.proxySocket = directSock;
		localIP = directSock.getLocalAddress();
		localPort = directSock.getLocalPort();
	} catch (final IOException io_ex) {
		final int errCode = SocksProxyBase.SOCKS_DIRECT_FAILED;
		throw new SocksException(errCode, "Direct connect failed:", io_ex);
	}
}
 
Example 10
Source File: Selector.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Generate an unique connection id
 * @param channel The channel between two hosts
 * @return The id for the connection that was created
 */
private String generateConnectionId(SocketChannel channel) {
  Socket socket = channel.socket();
  String localHost = socket.getLocalAddress().getHostAddress();
  int localPort = socket.getLocalPort();
  String remoteHost = socket.getInetAddress().getHostAddress();
  int remotePort = socket.getPort();
  long connectionIdSuffix = idGenerator.getAndIncrement();
  return localHost + ":" + localPort + "-" + remoteHost + ":" + remotePort + "_" + connectionIdSuffix;
}
 
Example 11
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 12
Source File: AgentWorker.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public AgentWorker(NbJShellAgent agent, Socket controlSocket) {
    this.agent = agent;
    this.socket = controlSocket;
    this.socketPort = controlSocket.getLocalPort();
    setup();
}
 
Example 13
Source File: ExchangeImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
public InetSocketAddress getLocalAddress() {
   Socket s = this.connection.getChannel().socket();
   InetAddress ia = s.getLocalAddress();
   int port = s.getLocalPort();
   return new InetSocketAddress(ia, port);
}
 
Example 14
Source File: NetworkHostNameResolver.java    From PADListener with GNU General Public License v2.0 4 votes vote down vote up
@Override
public SiteData getSecureHost(Socket socket, int _destPort, boolean _getCertificateData) {
    SiteData secureHost = null;
    int port =  socket.getPort();
    int localport =  socket.getLocalPort();
    if (LOGD) Log.d(TAG, "Search site for port " + port + " local:" + localport);
    SiteData secureHostInit = parseData(socket, _destPort);
    if (!_getCertificateData){
        return secureHostInit;
    }
    getCertificateData(secureHostInit);
    if (siteData.size() == 0 || !siteData.containsKey(port)){
        try {
            for(int i=0; i < 100; i++){
                Thread.sleep(100);
                if (siteData.containsKey(port)){
                    secureHost = siteData.get(port);
                    break;
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    if (secureHost == null && siteData.containsKey(port)){
        secureHost = siteData.get(port);
    }
    if (secureHost == null && mHostName != null && mHostName.length() > 0){
        secureHost =  new SiteData();
        secureHost.name = mHostName;
    }
    if (secureHost == null){
        if (LOGD) Log.d(TAG, "Nothing found for site for port " + port);
        return secureHostInit;
    }else{
        if (LOGD) Log.d(TAG, "Having site for port " + port + " " 
                +  secureHost.name + " addr: " 
                + secureHost.tcpAddress 
                + " port " + secureHost.destPort);
    }
    return secureHost;
}
 
Example 15
Source File: ExchangeImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
public InetSocketAddress getLocalAddress() {
   Socket s = this.connection.getChannel().socket();
   InetAddress ia = s.getLocalAddress();
   int port = s.getLocalPort();
   return new InetSocketAddress(ia, port);
}
 
Example 16
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 17
Source File: BHttpConnectionBase.java    From java-android-websocket-client with Apache License 2.0 4 votes vote down vote up
@Override
public int getLocalPort() {
    final Socket socket = this.socketHolder.get();
    return socket != null ? socket.getLocalPort() : -1;
}
 
Example 18
Source File: HandShake.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public ServerQueueStatus greet(Connection conn, ServerLocation location, byte communicationMode) throws IOException,
    AuthenticationRequiredException, AuthenticationFailedException,
    ServerRefusedConnectionException {
  try {
    ServerQueueStatus serverQStatus = null;
    Socket sock = conn.getSocket();
    DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
    final InputStream in = sock.getInputStream();
    DataInputStream dis = new DataInputStream(in);
    DistributedMember member = getDistributedMember(sock);
    // if running in a loner system, use the new port number in the ID to 
    // help differentiate from other clients
    DM dm = ((InternalDistributedSystem)this.system).getDistributionManager();
    InternalDistributedMember idm = dm.getDistributionManagerId();
    synchronized(idm) {
      if (idm.getPort() == 0 && dm instanceof LonerDistributionManager) {
        int port = sock.getLocalPort();
        ((LonerDistributionManager)dm).updateLonerPort(port);
        updateProxyID(dm.getDistributionManagerId());
      }
    }
    if(communicationMode == Acceptor.GATEWAY_TO_GATEWAY) {
      this.credentials = getCredentials(member);
    }
    byte intermediateAcceptanceCode = write(dos, dis, communicationMode,
        REPLY_OK, this.clientReadTimeout, null, this.credentials, member,
        false);
    
    String authInit = this.system.getProperties().getProperty(
        DistributionConfig.SECURITY_CLIENT_AUTH_INIT_NAME);
    if (communicationMode != Acceptor.GATEWAY_TO_GATEWAY
        && intermediateAcceptanceCode != REPLY_AUTH_NOT_REQUIRED
        && (authInit != null && authInit.length() != 0)) {
      location.compareAndSetRequiresCredentials(true);
    }
    // Read the acceptance code
    byte acceptanceCode = dis.readByte();
    if (acceptanceCode == (byte)21 && !(sock instanceof SSLSocket)) {
      // This is likely the case of server setup with SSL and client not using
      // SSL
      throw new AuthenticationRequiredException(
        LocalizedStrings.HandShake_SERVER_EXPECTING_SSL_CONNECTION
        .toLocalizedString());
    }
    
    //Successful handshake for GATEWAY_TO_GATEWAY mode sets the peer version in connection
    if(communicationMode == Acceptor.GATEWAY_TO_GATEWAY  && !
        (acceptanceCode == REPLY_EXCEPTION_AUTHENTICATION_REQUIRED ||
            acceptanceCode ==  REPLY_EXCEPTION_AUTHENTICATION_FAILED)) {
        conn.setWanSiteVersion(Version.readOrdinal(dis));
      } 

    // No need to check for return value since DataInputStream already throws
    // EOFException in case of EOF
    byte epType = dis.readByte();
    int qSize = dis.readInt();

    // Read the server member
    member = readServerMember(dis);
    serverQStatus = new ServerQueueStatus(epType, qSize,member);

    // Read the message (if any)
    readMessage(dis, dos, acceptanceCode, member);

    // Read delta-propagation property value from server.
    // [sumedh] Static variable below? Client can connect to different
    // DSes with different values of this. It shoule be a member variable.
    if (communicationMode != Acceptor.GATEWAY_TO_GATEWAY
        && currentClientVersion >= Version.GFE_61.ordinal()) {
      deltaEnabledOnServer = dis.readBoolean();
    }

    //validate that the remote side has a different distributed system id.
    if (communicationMode == Acceptor.GATEWAY_TO_GATEWAY
        && conn.getWanSiteVersion() >= Version.GFE_66.ordinal()
        && currentClientVersion >= Version.GFE_66.ordinal()) {
      int remoteDistributedSystemId = in.read();
      int localDistributedSystemId = ((InternalDistributedSystem) system).getDistributionManager().getDistributedSystemId();
      if(localDistributedSystemId >= 0 && localDistributedSystemId == remoteDistributedSystemId) {
        throw new GatewayConfigurationException(
            "Remote WAN site's distributed system id "
                + remoteDistributedSystemId
                + " matches this sites distributed system id "
                + localDistributedSystemId);
      }
    }

    return serverQStatus;
  }
  catch (IOException ex) {
    CancelCriterion stopper = this.system.getCancelCriterion();
    stopper.checkCancelInProgress(null);
    throw ex;
  }
}
 
Example 19
Source File: HandShake.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public ServerQueueStatus greet(Connection conn, ServerLocation location, byte communicationMode) throws IOException,
    AuthenticationRequiredException, AuthenticationFailedException,
    ServerRefusedConnectionException {
  try {
    ServerQueueStatus serverQStatus = null;
    Socket sock = conn.getSocket();
    DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
    final InputStream in = sock.getInputStream();
    DataInputStream dis = new DataInputStream(in);
    DistributedMember member = getDistributedMember(sock);
    // if running in a loner system, use the new port number in the ID to 
    // help differentiate from other clients
    DM dm = ((InternalDistributedSystem)this.system).getDistributionManager();
    InternalDistributedMember idm = dm.getDistributionManagerId();
    synchronized(idm) {
      if (idm.getPort() == 0 && dm instanceof LonerDistributionManager) {
        int port = sock.getLocalPort();
        ((LonerDistributionManager)dm).updateLonerPort(port);
        updateProxyID(dm.getDistributionManagerId());
      }
    }
    if(communicationMode == Acceptor.GATEWAY_TO_GATEWAY) {
      this.credentials = getCredentials(member);
    }
    byte intermediateAcceptanceCode = write(dos, dis, communicationMode,
        REPLY_OK, this.clientReadTimeout, null, this.credentials, member,
        false);
    
    String authInit = this.system.getProperties().getProperty(
        DistributionConfig.SECURITY_CLIENT_AUTH_INIT_NAME);
    if (communicationMode != Acceptor.GATEWAY_TO_GATEWAY
        && intermediateAcceptanceCode != REPLY_AUTH_NOT_REQUIRED
        && (authInit != null && authInit.length() != 0)) {
      location.compareAndSetRequiresCredentials(true);
    }
    // Read the acceptance code
    byte acceptanceCode = dis.readByte();
    if (acceptanceCode == (byte)21 && !(sock instanceof SSLSocket)) {
      // This is likely the case of server setup with SSL and client not using
      // SSL
      throw new AuthenticationRequiredException(
        LocalizedStrings.HandShake_SERVER_EXPECTING_SSL_CONNECTION
        .toLocalizedString());
    }
    
    //Successful handshake for GATEWAY_TO_GATEWAY mode sets the peer version in connection
    if(communicationMode == Acceptor.GATEWAY_TO_GATEWAY  && !
        (acceptanceCode == REPLY_EXCEPTION_AUTHENTICATION_REQUIRED ||
            acceptanceCode ==  REPLY_EXCEPTION_AUTHENTICATION_FAILED)) {
        conn.setWanSiteVersion(Version.readOrdinal(dis));
      } 

    // No need to check for return value since DataInputStream already throws
    // EOFException in case of EOF
    byte epType = dis.readByte();
    int qSize = dis.readInt();

    // Read the server member
    member = readServerMember(dis);
    serverQStatus = new ServerQueueStatus(epType, qSize,member);

    // Read the message (if any)
    readMessage(dis, dos, acceptanceCode, member);

    // Read delta-propagation property value from server.
    // [sumedh] Static variable below? Client can connect to different
    // DSes with different values of this. It shoule be a member variable.
    if (communicationMode != Acceptor.GATEWAY_TO_GATEWAY
        && currentClientVersion >= Version.GFE_61.ordinal()) {
      deltaEnabledOnServer = dis.readBoolean();
    }

    //validate that the remote side has a different distributed system id.
    if (communicationMode == Acceptor.GATEWAY_TO_GATEWAY
        && conn.getWanSiteVersion() >= Version.GFE_66.ordinal()
        && currentClientVersion >= Version.GFE_66.ordinal()) {
      int remoteDistributedSystemId = in.read();
      int localDistributedSystemId = ((InternalDistributedSystem) system).getDistributionManager().getDistributedSystemId();
      if(localDistributedSystemId >= 0 && localDistributedSystemId == remoteDistributedSystemId) {
        throw new GatewayConfigurationException(
            "Remote WAN site's distributed system id "
                + remoteDistributedSystemId
                + " matches this sites distributed system id "
                + localDistributedSystemId);
      }
    }

    return serverQStatus;
  }
  catch (IOException ex) {
    CancelCriterion stopper = this.system.getCancelCriterion();
    stopper.checkCancelInProgress(null);
    throw ex;
  }
}
 
Example 20
Source File: NetUtils.java    From big-c 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.");
  }
}