httparty icon indicating copy to clipboard operation
httparty copied to clipboard

local_port and local_host

Open Aethelflaed opened this issue 7 years ago • 0 comments

After finding this question, I found that whenever a local_port is specified, it will automatically assume that we try to bind to localhost, as per getaddrinfo(3):

   If the AI_PASSIVE flag is not set in hints.ai_flags, then the returned socket
   addresses will be suitable for use with connect(2), sendto(2), or sendmsg(2).
   If node is NULL, then the network address will be set to the loopback  inter‐
   face  address  (INADDR_LOOPBACK for IPv4 addresses, IN6ADDR_LOOPBACK_INIT for
   IPv6 address); this is used by applications that intend to  communicate  with
   peers running on the same host.

However, binding on a loopback address makes the network unreachable.

For the low level ruby API this is desirable as it may be needed, for Net::HTTP it may still be used this way, but for a higher level library such as HTTParty, this behavior seems inconsistent and illogical, as it basically breaks the expected behavior:

HTTParty.get 'http://google.com', local_port: 60000
# Errno::ENETUNREACH: Failed to open TCP connection to google.com:80 (Network is unreachable - connect(2) for "google.com" port 80)

Specifying the local_host to localhost or 127.0.0.1 produces two different kind of errors if you try to access and external service:

HTTParty.get 'http://google.com', local_host: 'localhost'
# Errno::ENETUNREACH: Failed to open TCP connection to google.com:80 (Network is unreachable - connect(2) for "google.com" port 80)
HTTParty.get 'http://google.com', local_host: '127.0.0.1'
# Errno::EINVAL: Failed to open TCP connection to google.com:80 (Invalid argument - connect(2) for "google.com" port 80)

# but both works if you indeed try to access a local service
HTTParty.get 'http://localhost:3000', local_host: '127.0.0.1'

As such, would it be possible to document that in the comments where we can find local_port, and maybe prevent setting local_port with local_host nil?

This way we can see somewhere that setting local_port requires a local_host too, and also that specifying 127.0.0.1 for the local_host prevents any connection to an external service.

Aethelflaed avatar Aug 14 '18 11:08 Aethelflaed