Last active
November 6, 2018 23:57
-
-
Save Freaky/09553b6ce61f7129e74bd7252e23c76d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module IpTest | |
module V4 | |
MAX_LEN = '255.255.255.255'.size | |
SEGMENT = /(?:25[0-5]|(?:2[0-4]|1?[0-9])?[0-9])/ | |
PATTERN = /#{SEGMENT}\.#{SEGMENT}\.#{SEGMENT}\.#{SEGMENT}/ | |
PATTERN_ANCHORED = /\A#{PATTERN}\z/ | |
def self.contains?(str) | |
PATTERN.match?(str) | |
end | |
def self.match?(str) | |
str.size <= MAX_LEN && PATTERN_ANCHORED.match?(str) | |
end | |
end | |
module V6 | |
MAX_LEN = 'ffff:ffff:ffff:ffff:ffff:ffff.255.255.255.255'.size | |
FILTER = /\A[0-9a-fA-F:\.]{2,45}\z/ | |
SEGMENT = /[0-9a-fA-F]{1,4}/ | |
PATTERN_8HEX = /(?:#{SEGMENT}:){7}#{SEGMENT}/ | |
PATTERN_COMPRESSED = /(?:#{SEGMENT}(?::#{SEGMENT}){0,7})?::(?:#{SEGMENT}(?::#{SEGMENT}){0,7})?/ | |
PATTERN_6HEX4DEC = /(?:#{SEGMENT}:#{SEGMENT}:#{SEGMENT}:#{SEGMENT}:#{SEGMENT}:#{SEGMENT}:#{SEGMENT}):#{V4::PATTERN}/ | |
PATTERN_6HEX4DEC_COMPRESSED = /(?:#{SEGMENT}(?::#{SEGMENT}){1,4})?::(?:#{SEGMENT}(?::#{SEGMENT}){1,4})?:#{V4::PATTERN}/ | |
PATTERN = /#{PATTERN_8HEX}|#{PATTERN_COMPRESSED}|#{PATTERN_6HEX4DEC}|#{PATTERN_6HEX4DEC_COMPRESSED}/ | |
PATTERN_ANCHORED = /\A(?:#{PATTERN})\z/ | |
def self.contains?(str) | |
PATTERN.match?(str) | |
end | |
def self.match?(str) | |
str.size <= MAX_LEN && FILTER.match?(str) && PATTERN_ANCHORED.match?(str) | |
end | |
end | |
def self.contains?(str) | |
V4.contains?(str) || V6.contains?(str) | |
end | |
def self.match?(str) | |
V4.match?(str) || V6.match?(str) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment