when I do this
ip = request.env["REMOTE_ADDR"]
I get the client's IP address it it. But what if I want to validate whether the value in the variable is really an IP? How do I do that?
Please help. Thanks in advance. And sorry if this question is repeated, I didn't take the effort of finding it...
EDIT
What about IPv6 IP's??
address is a string or integer representing the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default.
Python program to check if a string is a valid IP address or not 1 The element should consist of numeric characters only. We will implement this with the help of the isnumeric ()... 2 The numeric value of the element lies in the inclusive range of 0 to 255. More ...
To determine whether a string is a valid representation of a specified numeric type, use the static TryParse method that is implemented by all primitive numeric types and also by types such as DateTime and IPAddress. The following example shows how to determine whether "108" is a valid int. C#.
Instead just pass the string as-is to the network components that will be using the IP address and let them do the validation. Catch the exceptions they will throw when it is wrong and use that information to tell the user what happened.
IP address in a string form must contain exactly four numbers, separated by dots. Each number must be in a range between 0 and 255, inclusive. Share Follow answered Sep 3 '10 at 10:51
Ruby has already the needed Regex in the standard library. Checkout resolv.
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
If you like it the short way ...
require "resolv" !!("192.168.1.1" =~ Resolv::IPv4::Regex) #=> true !!("192.168.1.500" =~ Resolv::IPv4::Regex) #=> false !!("ff02::1" =~ Resolv::IPv6::Regex) #=> true !!("ff02::1::1" =~ Resolv::IPv6::Regex) #=> false
Have fun!
Update (2018-10-08):
From the comments below i love the very short version:
!!(ip_string =~ Regexp.union([Resolv::IPv4::Regex, Resolv::IPv6::Regex]))
Very elegant with rails (also an answer from below):
validates :ip, :format => { :with => Regexp.union(Resolv::IPv4::Regex, Resolv::IPv6::Regex) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With