sparklemotion / mechanize

Mechanize is a ruby library that makes automated web interaction easy.
https://www.rubydoc.info/gems/mechanize/
MIT License
4.39k stars 473 forks source link

What's the RIGHT way to accomplish controlling the source IP and port with Mechanize? #595

Closed astounding closed 2 years ago

astounding commented 2 years ago

I didn't see anything obvious in documentation showing how to control the SOURCE IP and PORT that Mechanize binds to. I know Net::HTTP has #local_port and #local_host methods to set and control source IP and PORT binding, but I don't know how to tell my Mechanize agent to set those. Instead I resorted to this UGLY kludge:

... ruby script body ...

BIND_IP = '192.168.55.121'  ## Totally bogus IP for example purposes

## ===============
## START OF KLUDGE
## ===============
## KLUDGE work-around for Mechanize NOT supporting binding to source IP
## and port:
##
## Rewrite Net::HTTP::Persistent::Connection#initialize() from
## /usr/local/lib/ruby/gems/2.7/gems/net-http-persistent-4.0.1/lib/net/http/persistent/connection.rb
## to set the local host and port we want to bind to for the connection.
## There has GOT to be a way to pass these options in legitimately
## instead of using a kludge like this.  An elegant, right way to do it.
class Net::HTTP::Persistent::Connection
  def initialize http_class, http_args, ssl_generation
    @http           = http_class.new(*http_args)
    @ssl_generation = ssl_generation

    ## SOURCE IP we want to bind to
    @http.local_host = BIND_IP
    @http.local_port = 0

    reset
  end
end
## =============
## END OF KLUDGE
## =============

... ruby script body that uses Mechanize ...

Is there a way to pass parameters or options to Mechanize either upon agent creation OR when executing the agent's #get or #post methods so that it sets @http.local_host instead of me having to resort to using this nasty kludge just to force the TCP HTTP socket to bind to the local IP I choose for the outgoing client connection(s)?

Thanks in advance for any pointers/tips/suggestions!

--Aaron out.