Skip to content
Snippets Groups Projects
Commit 72f3d83d authored by Wojciech Pietrzak's avatar Wojciech Pietrzak
Browse files

use builtin libs to validate ips

parent 8996a99b
Branches
Tags
No related merge requests found
require 'resolv'
module Geocoder module Geocoder
class IpAddress < String class IpAddress < String
...@@ -6,16 +7,7 @@ module Geocoder ...@@ -6,16 +7,7 @@ module Geocoder
end end
def valid? def valid?
ipregex = %r{ !!((self =~ Resolv::IPv4::Regex) || (self =~ Resolv::IPv6::Regex))
\A( # String Starts
((::ffff:)?((\d{1,3})\.){3}\d{1,3}) # Check for IPv4
| # .... Or
(\S+?(:\S+?){6}\S+) # Check for IPv6
| # .... Or
(::1) # IPv6 loopback
)\z
}x
!!self.match(ipregex)
end end
end end
end end
...@@ -6,7 +6,7 @@ class IpAddressTest < GeocoderTestCase ...@@ -6,7 +6,7 @@ class IpAddressTest < GeocoderTestCase
def test_valid def test_valid
assert Geocoder::IpAddress.new("232.65.123.94").valid? assert Geocoder::IpAddress.new("232.65.123.94").valid?
assert Geocoder::IpAddress.new("666.65.123.94").valid? # technically invalid assert !Geocoder::IpAddress.new("666.65.123.94").valid?
assert Geocoder::IpAddress.new("::ffff:12.34.56.78").valid? assert Geocoder::IpAddress.new("::ffff:12.34.56.78").valid?
assert Geocoder::IpAddress.new("3ffe:0b00:0000:0000:0001:0000:0000:000a").valid? assert Geocoder::IpAddress.new("3ffe:0b00:0000:0000:0001:0000:0000:000a").valid?
assert Geocoder::IpAddress.new("::1").valid? assert Geocoder::IpAddress.new("::1").valid?
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment