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??
Ruby has already the needed Regex in the standard library. Checkout resolv.
If you like it the short way ...
Have fun!
Update (2018-10-08):
From the comments below i love the very short version:
Very elegant with rails (also an answer from below):
for match a valid IP adress with regexp use
instead of
because many regex engine match the first possibility in the OR sequence
you can try your regex engine : 10.48.0.200
test the difference here
All answers above asume IPv4... you must ask yourself how wise it is to limit you app to IPv4 by adding these kind of checks in this day of the net migrating to IPv6.
If you ask me: Don't validate it at all. 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. Don't re-invent the wheel, build upon the work of others.
Try this
Use
IPAddr
This regular expression I use which I found here
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
Use http://www.ruby-doc.org/stdlib-1.9.3/libdoc/ipaddr/rdoc/IPAddr.html it performs validation for you. Just rescue the exception with false and you know that it was invalid.