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??
I use it for quick check because it uses built in library. Supports both ipv4 and ipv6. It is not very strict though, it says '999.999.999.999' is valid, for example. See the winning answer if you need more precision.
Or, if you don't mind extending core classes:
Why not let a library validate it for you? You shouldn't introduce complex regular expressions that are impossible to maintain.
Then, in your application
You can also use Ruby's built-in
IPAddr
class, but it doesn't lend itself very well for validation.Of course, if the IP address is supplied to you by the application server or framework, there is no reason to validate at all. Simply use the information that is given to you, and handle any exceptions gracefully.
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.
As most of the answers don't speak about IPV6 validation, I had the similar problem. I solved it by using the Ruby Regex Library, as @wingfire mentionned it.
But I also used the Regexp Library to use it's
union
method as explained hereI so have this code for a validation :
Hope this can help someone !
Validate using regular expression: