How do I check whether a value in a string is an IP address

Viewed 25884

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

13 Answers

for match a valid IP adress with regexp use

^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$

instead of

^([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])(\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])){3}$

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

for ipv4

def ipv4?(str)
   nums = str.split('.')
   reg = /^\d$|^[1-9]\d$|^1\d\d$|^2[0-4]\d$|^25[0-5]$/
   nums.length == 4 && (nums.count {|n| reg.match?(n)}) == 4
end
Related