Skip to content

Instantly share code, notes, and snippets.

@nilium
Forked from havenwood/valid-ipv4.rb
Last active December 20, 2015 07:29
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 nilium/6093291 to your computer and use it in GitHub Desktop.
Save nilium/6093291 to your computer and use it in GitHub Desktop.
module Valid
OCTET_RANGE = (0 .. 255)
def self.ipv4?(address)
octets = address.split '.'
octets.length == 4 && octets.all? { |octet|
octet_i = octet.to_i
(0..255).cover?(octet_i) && octet_i.to_s(10) == octet
}
end
end
Valid.ipv4? "192.168.1.1"
# => true
Valid.ipv4? "192.168.1.1.1"
# => false
Valid.ipv4? "256.168.1.1"
# => false
Valid.ipv4? "256.168.1.0x1"
# => false
Valid.ipv4? "I would shiver the whole night through."
# => false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment