From: Colin Watson <cjwatson@debian.org>
Date: Mon, 26 Aug 2024 01:30:07 +0100
Subject: Deduplicate results from getaddrinfo

In certain configurations it's possible to get duplicate results back
from getaddrinfo: for example, if you accidentally have more than one
line in /etc/hosts mapping the same name to the same IP address, then
Linux/glibc systems will return multiple identical entries.  This minor
misconfiguration is normally harmless, but it caused this program to
fail with `EADDRINUSE`:

    require 'socket'
    Socket.tcp_server_sockets('localhost', 0)

Prior to https://github.com/ruby/net-http/pull/180, this caused a number
of `TestNetHTTP*` tests to fail, as seen in these Debian bugs:

  https://bugs.debian.org/1069399 (Ruby 3.1)
  https://bugs.debian.org/1064685 (Ruby 3.2)
  https://bugs.debian.org/1077462 (Ruby 3.3)

It's easy enough to deduplicate these.
---
 ext/socket/lib/socket.rb | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/ext/socket/lib/socket.rb b/ext/socket/lib/socket.rb
index de54222..12955e2 100644
--- a/ext/socket/lib/socket.rb
+++ b/ext/socket/lib/socket.rb
@@ -673,10 +673,16 @@ class Socket < BasicSocket
   # :stopdoc:
   def self.ip_sockets_port0(ai_list, reuseaddr)
     sockets = []
+    ai_seen = {}
     begin
       sockets.clear
       port = nil
       ai_list.each {|ai|
+        ai_id = [ai.pfamily, ai.socktype, ai.protocol, ai.ip_address]
+        if ai_seen.include?(ai_id)
+          next
+        end
+        ai_seen[ai_id] = nil
         begin
           s = Socket.new(ai.pfamily, ai.socktype, ai.protocol)
         rescue SystemCallError
