Skip to content

Instantly share code, notes, and snippets.

@Freaky
Last active November 6, 2018 23:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Freaky/09553b6ce61f7129e74bd7252e23c76d to your computer and use it in GitHub Desktop.
Save Freaky/09553b6ce61f7129e74bd7252e23c76d to your computer and use it in GitHub Desktop.
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