views:

113

answers:

5

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...

A: 

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.

squadette
also remember that you have to check for local network ips and other reserved ip addresses like 192.168.x.x and 127.0.0.1
corroded
why? you actually can access your own site from your own network :) (or even with lynx on localhost).
squadette
A: 

Validate using regular expression:

\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}
Ankit Jain
999.999.999.999 is not a valid IP address
captaintokyo
ooh for that rigorous check use the one specified here: http://www.regular-expressions.info/regexbuddy/ipaccurate.html
Ankit Jain
Thanks for the link.. interesting
captaintokyo
A: 

This regular expresion 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]?)$/

Gerhard
+3  A: 

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.

Stijn de Witt
btw, what u get in `request.env['REMOTE_ADDR']` will always be a valid IP address, unless the web-server mess up with it! There is no need to check
Ankit Jain
+5  A: 

Why not let a library validate it for you? You shouldn't introduce complex regular expressions that are impossible to maintain.

% gem install ipaddress

Then, in your application

require "ipaddress"

IPAddress.valid? "192.128.0.12"
#=> true

IPAddress.valid? "192.128.0.260"
#=> false

# Validate IPv6 addresses without additional work.
IPAddress.valid? "ff02::1"
#=> true

IPAddress.valid? "ff02::ff::1"
#=> false

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.

molf