Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active December 20, 2015 07:29
Show Gist options
  • Save havenwood/6093223 to your computer and use it in GitHub Desktop.
Save havenwood/6093223 to your computer and use it in GitHub Desktop.
Check IPV4 validity with a bit more particularity than IPAddr::RE_IPV4ADDRLIKE.
def ipv4? string
octets = string.split '.'
octets.size == 4 && octets.all? do |octet|
octet == octet.to_i.to_s(10) && (0..255).cover?(octet.to_i)
end
end
ipv4? '192.168.1.1'
#=> true
ipv4? '192.168.1.1.1'
#=> false
ipv4? '256.168.1.1'
#=> false
ipv4? '0x1.0x1.0x1.0x1'
#=> false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment