File: ip_address.rb

package info (click to toggle)
ruby-geocoder 1.8.6-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 900 kB
  • sloc: ruby: 8,419; makefile: 3
file content (36 lines) | stat: -rw-r--r-- 745 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
require 'resolv'
module Geocoder
  class IpAddress < String
    PRIVATE_IPS = [
      '10.0.0.0/8',
      '172.16.0.0/12',
      '192.168.0.0/16',
    ].map { |ip| IPAddr.new(ip) }.freeze

    def initialize(ip)
      ip = ip.to_string if ip.is_a?(IPAddr)
      if ip.is_a?(Hash)
        super(**ip)
      else
        super(ip)
      end
    end

    def internal?
      loopback? || private?
    end

    def loopback?
      valid? and !!(self == "0.0.0.0" or self.match(/\A127\./) or self == "::1")
    end

    def private?
      valid? && PRIVATE_IPS.any? { |ip| ip.include?(self) }
    end

    def valid?
      ip = self[/(?<=\[)(.*?)(?=\])/] || self
      !!((ip =~ Resolv::IPv4::Regex) || (ip =~ Resolv::IPv6::Regex))
    end
  end
end