Method: Rex::Socket.getaddresses

Defined in:
lib/rex/socket.rb

.getaddresses(hostname, accept_ipv6 = true) ⇒ Array<String>

Wrapper for ::Socket.gethostbyname that takes special care to see if the supplied address is already an ASCII IP address. This is necessary to prevent blocking while waiting on a DNS reverse lookup when we already have what we need.



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/rex/socket.rb', line 176

def self.getaddresses(hostname, accept_ipv6 = true)
  if hostname =~ MATCH_IPV4 or (accept_ipv6 and hostname =~ MATCH_IPV6)
    return [hostname]
  end

  res = ::Socket.gethostbyname(hostname)
  return [] if not res

  # Shift the first three elements out, leaving just the list of
  # addresses
  res.shift # name
  res.shift # alias hostnames
  res.shift # address_family

  # Rubinius has a bug where gethostbyname returns dotted quads instead of
  # NBO, but that's what we want anyway, so just short-circuit here.
  if res[0] =~ MATCH_IPV4 || res[0] =~ MATCH_IPV6
    unless accept_ipv6
      res.reject!{ |ascii| ascii =~ MATCH_IPV6 }
    end
  else
    unless accept_ipv6
      res.reject!{ |nbo| nbo.length != 4 }
    end
    res.map!{ |nbo| self.addr_ntoa(nbo) }
  end

  res
end