我的应用程序( Rails使用jRuby、puma、CentOS 6上的nginx )希望向远程REST服务直接提出服务器到服务器的请求。我的应用程序与服务的网络不同,这意味着IT部门必须配置防火墙,以便允许这些请求。
他们想知道
除了源端口之外,一切都很简单。我的应用程序是否可能只使用一个端口?如果没有,我至少可以给出一系列的端口吗?这是如何配置的?
发布于 2018-08-14 08:53:45
解决方案
我刚刚看到了httparty,您可以使用:local_port和:local_host请求选项:
显然,如果要指定local_host,则必须指定local_port,这是一直到Socket的限制,可能还有事件connect(2)。
# Get the first local IP address which is not the loopback
# There are far better way of doing this, this is just for the example
addr = Socket.ip_address_list.select(&:ipv4?).detect{|addr| addr.ip_address != '127.0.0.1'}
# Start a connection using a predefined port
HTTParty.get 'http://google.com', local_port: 60000, local_host: addr.ip_address如果要覆盖本地端口,则必须同时指定local_host和local_port,原因是套接字使用Addrinfo.getaddrinfo,如果只指定端口,则返回回送地址。
这要归功于getaddrinfo(3)
如果AI_PASSIVE标志未在hints.ai_flags中设置,则返回的套接字地址将适合与connect(2)、sendto(2)或sendmsg(2)一起使用。如果节点为NULL,则网络地址将设置为回送接口地址(INADDR_LOOPBACK表示IPv4地址,IN6ADDR_LOOPBACK_INIT表示IPv6地址);这将被打算与在同一主机上运行的对等程序通信的应用程序使用。
在这种情况下,AI_PASSIVE不是设置的,因为我们不想使用bind,而是要设置为connect。
使用回环地址,外部网络是无法到达的,这就是为什么我们也需要指定local_host。
原始答案
您可以首先创建Net::HTTP实例,然后在启动连接之前配置local_port ( R/W属性)。
如果使用任何其他方法来建立连接,则可能需要检查文档,以确定是否有可用的方法。
http = Net::HTTP.new(address, port)
http.local_port = 666
http.local_host = 'your ip address'
http.start do
# whatever
endlocal_port是一个attr_accessor,@local_port直接用于打开TCP套接字:TCPSocket.open(conn_address, conn_port, @local_host, @local_port)。
https://stackoverflow.com/questions/51836680
复制相似问题