Skip to content

Commit

Permalink
Use port number 0 for ephemeral port if save
Browse files Browse the repository at this point in the history
On platforms where ephemeral port randomization is implemented, the
same randomization is not needed in the ruby library layer.

Fixes #63.
  • Loading branch information
nobu committed Jan 21, 2025
1 parent 320a179 commit 45e1b56
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions lib/resolv.rb
Original file line number Diff line number Diff line change
Expand Up @@ -659,8 +659,20 @@ def self.free_request_id(host, port, id) # :nodoc:
}
end

def self.bind_random_port(udpsock, bind_host="0.0.0.0") # :nodoc:
begin
case RUBY_PLATFORM
when *[
# https://www.rfc-editor.org/rfc/rfc6056.txt
# Appendix A. Survey of the Algorithms in Use by Some Popular Implementations
/freebsd/, /linux/, /netbsd/, /openbsd/, /solaris/,
/darwin/, # the same as FreeBSD
] then
def self.bind_random_port(udpsock, bind_host="0.0.0.0") # :nodoc:
udpsock.bind(bind_host, 0)
end
else
# Sequential port assignment
def self.bind_random_port(udpsock, bind_host="0.0.0.0") # :nodoc:
# Ephemeral port number range recommended by RFC 6056
port = random(1024..65535)
udpsock.bind(bind_host, port)
rescue Errno::EADDRINUSE, # POSIX
Expand Down

0 comments on commit 45e1b56

Please sign in to comment.