Skip to content

Instantly share code, notes, and snippets.

@Achillefs
Created November 29, 2010 14:51
Show Gist options
  • Save Achillefs/720034 to your computer and use it in GitHub Desktop.
Save Achillefs/720034 to your computer and use it in GitHub Desktop.
Net::HTTP with multiple bind address functionality
require "net/http"
module Net
class HTTP
alias :old_connect :connect
def connect
D "opening connection to #{conn_address()}..."
begin # HACK START
s = timeout(@open_timeout) do
TCPSocket.open(conn_address(), conn_port(), App.available_ip_addresses.rand)
end
rescue NameError # means App is not initialized
s = timeout(@open_timeout) { TCPSocket.open(conn_address(), conn_port()) }
end # HACK END
D "opened"
if use_ssl?
ssl_parameters = Hash.new
iv_list = instance_variables
SSL_ATTRIBUTES.each do |name|
ivname = "@#{name}".intern
if iv_list.include?(ivname) and
value = instance_variable_get(ivname)
ssl_parameters[name] = value
end
end
@ssl_context = OpenSSL::SSL::SSLContext.new
@ssl_context.set_params(ssl_parameters)
s = OpenSSL::SSL::SSLSocket.new(s, @ssl_context)
s.sync_close = true
end
@socket = BufferedIO.new(s)
@socket.read_timeout = @read_timeout
@socket.debug_output = @debug_output
if use_ssl?
if proxy?
@socket.writeline sprintf('CONNECT %s:%s HTTP/%s',
@address, @port, HTTPVersion)
@socket.writeline "Host: #{@address}:#{@port}"
if proxy_user
credential = ["#{proxy_user}:#{proxy_pass}"].pack('m')
credential.delete!("\r\n")
@socket.writeline "Proxy-Authorization: Basic #{credential}"
end
@socket.writeline ''
HTTPResponse.read_new(@socket).value
end
s.connect
if @ssl_context.verify_mode != OpenSSL::SSL::VERIFY_NONE
s.post_connection_check(@address)
end
end
on_connect
end
private :connect
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment