Answer the question
In order to leave comments, you need to log in
How to check the correctness of the ip address in ruby?
There is a function that receives an ip address as an argument like this: http://127.34.72.163:82/test
How can you easily check that by passing an argument it is a correct ip address?
Googling, I found that there is a native library that checks the correctness of the IP
require "resolv"
"192.168.1.1" =~ Resolv::IPv4::Regex ? true : false #=> true
"192.168.1.500" =~ Resolv::IPv4::Regex ? true : false #=> false
"ff02::1" =~ Resolv::IPv6::Regex ? true : false #=> true
"ff02::1::1" =~ Resolv::IPv6::Regex ? true : false #=> false
http://
at the beginning and /test
after it, and with this argument, the library no longer works correctly. Perhaps you can check it somehow easier with regular expressions, or something else? Answer the question
In order to leave comments, you need to log in
require 'net/http'
def correctIpAddress?(source)
begin
url = URI.parse(source)
rescue URI::InvalidURIError
return false
rescue StandardError
raise
end
host = url.host
begin
ip = IPAddr.new host
rescue IPAddr::InvalidAddressError
return false
rescue StandardError
raise
end
return true
end
puts correctIpAddress?('https://example.com/foo') # valid url, no ip address
puts correctIpAddress?('foo bar 42 $%$%') # invalid url
puts correctIpAddress?('https://127.0.0.1/foo') # valid url, valid ip address
The above address is incorrect. This is a url, so take a library to check the url, get the host, check it with a regexp for the condition that each part is less than 256 and already accumulate this line to the ip parser. Or immediately do a regexp, isolate the numbers separated by 3 dots and give this result to your library for verification
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question