Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 918
Rohit Avatar asked Sep 03 '10 10:09

Rohit


People also ask

Is an IP address a string?

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.

How to check if a string is a valid IP address?

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

How do you check if a string is a valid int?

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

How to pass a string as an IP address?

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.

What is the IP address range for a string form?

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


1 Answers

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)           } 
like image 102
wingfire Avatar answered Sep 19 '22 23:09

wingfire