Re: Tricky socks question: changing source IP on Net::HTTP

I’ve got an interface with multiple IP addresses and I’m looking to
make HTTP requests from the non-primary IP.

How would I pull that off?

In principle, you ‘bind’ the socket to the correct local IP address
you ‘connect’

Unfortunately, TCPSocket#open (or #new) does the connect before it gives
a chance to bind. So you’ll need to replace with
messy along the lines of

s =, Socket::SOCK_STREAM, 

s.bind(Socket.pack_sockaddr_in(0, “”)) # chosen local IP
s.connect(Socket.pack_sockaddr_in(80, “”))

Test this and check that it works at the TCP layer, e.g. by adding

s.write("GET / HTTP/1.0\r\n\r\n")

If that works, then unfortunately net/http.rb doesn’t seem to have a
suitable hook, so copy the source and look for to see
you need to modify it.

Good luck,


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs