Module: Validators::Ip

Defined in:
lib/validators/ip.rb

Class Method Summary collapse

Class Method Details

.v4?(addr) ⇒ Boolean

Extracted from Ruby 1.8.7

Returns:

  • (Boolean)


6
7
8
9
# File 'lib/validators/ip.rb', line 6

def v4?(addr)
  matches = addr.match(/\A(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\Z/)
  matches&.captures&.all? {|i| i.to_i < 256 }
end

.v6?(addr) ⇒ Boolean

Extracted from Ruby 1.8.7

Returns:

  • (Boolean)


12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/validators/ip.rb', line 12

def v6?(addr)
  # IPv6 (normal)
  return true if /\A[\da-f]{1,4}(:[\da-f]{1,4})*\Z/i.match?(addr)
  return true if /\A[\da-f]{1,4}(:[\da-f]{1,4})*::([\da-f]{1,4}(:[\da-f]{1,4})*)?\Z/i.match?(addr)
  return true if /\A::([\da-f]{1,4}(:[\da-f]{1,4})*)?\Z/i.match?(addr)
  # IPv6 (IPv4 compat)
  return true if /\A[\da-f]{1,4}(:[\da-f]{1,4})*:/i =~ addr && v4?(Regexp.last_match.post_match)
  return true if /\A[\da-f]{1,4}(:[\da-f]{1,4})*::([\da-f]{1,4}(:[\da-f]{1,4})*:)?/i =~ addr && v4?(Regexp.last_match.post_match)
  return true if /\A::([\da-f]{1,4}(:[\da-f]{1,4})*:)?/i =~ addr && v4?(Regexp.last_match.post_match)

  false
end

.valid?(addr) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/validators/ip.rb', line 25

def valid?(addr)
  v4?(addr) || v6?(addr)
end