class Excon::Socket

def connect

def connect
  @socket = nil
  exception = nil
  addrinfo = if @proxy
    ::Socket.getaddrinfo(@proxy[:host], @proxy[:port].to_i, ::Socket::Constants::AF_UNSPEC, ::Socket::Constants::SOCK_STREAM)
  else
    ::Socket.getaddrinfo(@params[:host], @params[:port].to_i, ::Socket::Constants::AF_UNSPEC, ::Socket::Constants::SOCK_STREAM)
  end
  addrinfo.each do |_, port, _, ip, a_family, s_type|
    # nonblocking connect
    begin
      sockaddr = ::Socket.sockaddr_in(port, ip)
      socket = ::Socket.new(a_family, s_type, 0)
      #secs = Integer(timeout)
      #usecs = Integer((timeout - secs) * 1_000_000)
      #optval = [secs, usecs].pack("l_2")
      #sock.setsockopt Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, optval
      socket.connect_nonblock(sockaddr)
      @socket = socket
      break
    rescue Errno::EINPROGRESS
      IO.select(nil, [socket], nil, @params[:connect_timeout])
      begin
        socket.connect_nonblock(sockaddr)
        @socket = socket
        break
      rescue Errno::EISCONN
        @socket = socket
        break
      rescue SystemCallError => exception
        socket.close
        next
      end
    rescue SystemCallError => exception
      socket.close
      next
    end
  end
  unless @socket
    # this will be our last encountered exception
    raise exception
  end
end