LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   ip address REGEX (https://www.linuxquestions.org/questions/programming-9/ip-address-regex-81210/)

Robert0380 08-12-2003 04:34 AM

ip address REGEX
 
could someone give a regex that detects a VALID ip address:

note: 255.255.255.255 is valid in my book


i cant seem to write one.

i'm trying to parse a file of valid and invalid IP's and print the good ones, it's using egrep and there is 1 ip per line.

i had to do this in school once before but never got the answer.

tjm 08-12-2003 09:03 AM

dunno, in perl maybe something like this;

#IP is in $ip
@ip_bits = split(/\./,$ip);

die if(scalar(@ip_bits)<4);

foreach(@ip_bits)
{
$_ =~ s/\D//g;
die if($_ > 255 || $_ < 0);
}

Again, I am not too great with perl, but I think that does it... though it isn't a one-off regexp

Robert0380 08-12-2003 10:40 PM

perl...so cryptic looking, i dont know any perl but thanks.

Robert0380 08-12-2003 10:42 PM

wait, i can tell what that does.

im guessing split splits the ip with a "." delimitor and then tests each part to see if it is greater than 255. took a minute but i get it now.

Strike 08-12-2003 11:17 PM

Python:

Code:

def isIP(s):
    octets = s.split(".")
    for octet in octets:
        if not (int(octet) >= 0 and int(octet) <= 255):
            return False
    return True


Hko 08-13-2003 03:41 PM

If you really want to use egrep:
Code:

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

# Taken (modified) from the O'Reilly book "Mastering regular expressions" .

This assumes there only an IP-address on each line, nothing else, except leading and trailing spaces.

Also note that it accepts zero-padding, i.e. 001.002.003.004 will be valid. but this actually is a valid IP-address.

devoyage 08-13-2003 06:58 PM

I just did this the other day, try it out (perl):

1) Make some variables for the regex pattern (let me know if it breaks ;)
Code:

#
# Common strings:
#
                                                                               
$ips = 'IP Address:';
$ip  = '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
                                                                               
$mcs = 'MAC Address:';
$mc  = '\w{2}-\w{2}-\w{2}-\w{2}-\w{2}-\w{2}';

2) use whatever you like for matching, maybe something like:
Code:

if(grep(/$ip/,$some_string)){print 'you get the point';}

Strike 08-14-2003 02:51 AM

Quote:

Originally posted by devoyage
I just did this the other day, try it out (perl):

1) Make some variables for the regex pattern (let me know if it breaks ;)
Code:

#
# Common strings:
#
                                                                               
$ips = 'IP Address:';
$ip  = '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
                                                                               
$mcs = 'MAC Address:';
$mc  = '\w{2}-\w{2}-\w{2}-\w{2}-\w{2}-\w{2}';


The problem is that that matches 999.999.999.999 as a valid IP, which it isn't :)

Robert0380 08-14-2003 06:41 PM

thanks guys. the egrep example is the one i really needed.

im not using perl or python so i needed just a plain ole regex, but i will save all of the example becuase you never know. i will have to use python later on tho....have to learn it to teach it to my girlfriend because she has to take a class that uses it. i get to learn it for the sake of helping her out in the class (arent i a good boyfriend).

sk8guitar 08-14-2003 08:54 PM

perl will do it great. the example posted was correct

Robert0380 08-14-2003 10:45 PM

the egrep one works also by the way....so that's atleast 2 that have been tested.

kev82 08-15-2003 04:23 AM

does the python example work? wouldnt 123.123.123.123.123 pass? i cant see where it checks for the number of octets.
<edit>also, how does int() treat characters, if someone entered 46.abc.123.87, what would int(abc) evaluate to? hopefully not 0 because if it did then it would pass.

but i have to say, not knowing python/perl and not being very good at regex, the python example was the only one i could read, and i wouldnt want to have to maintain the others.

Strike 08-15-2003 09:52 AM

Quote:

Originally posted by kev82
does the python example work? wouldnt 123.123.123.123.123 pass? i cant see where it checks for the number of octets.
Yeah, it would. You can add a check for that, of course.

Quote:

<edit>also, how does int() treat characters, if someone entered 46.abc.123.87, what would int(abc) evaluate to? hopefully not 0 because if it did then it would pass.
It would raise an exception, as it should.

Quote:

but i have to say, not knowing python/perl and not being very good at regex, the python example was the only one i could read, and i wouldnt want to have to maintain the others.
:D

Here's the modified version to check for number of octets as well.

Code:

def isIP(s):
    octets = s.split(".")
    if len(octets) != 4: return False

    for octet in octets:
        if not (int(octet) >= 0 and int(octet) <= 255):
            return False
    return True


esben 08-15-2003 11:54 AM

Re: ip address REGEX
 
The answers above are all very well, but doesn't fully solve the problem :p

Quote:

Originally posted by Robert0380
i'm trying to parse a file of valid and invalid IP's and print the good ones, it's using egrep and there is 1 ip per line.
All fails to read in the file and to print out the result :D (Well, except maybe the egrep thing). Here's a solution in perl that includes a novel thing: indentation ;-) I wasn't sure if the ip-addresses were printed on the line without any noise except maybe whitespace. If this was the case, the 3rd line could be simply
@ipbits = split(/\./);

#!/usr/bin/perl -w
main: while(<>) {
@ipbits = /(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})?/; # pick out ip addresses
next unless (@ipbits); # verify pattern match
for (@ipbits) {
next main if ($_ <0 || $_>255); # verify ranges
}
print join('.',@ipbits)."\n"; # print valid numbers
}

The important things to know in order to read perl is:
1) Scalar variables are prefixed with $, arrays with @ and hashes with #
2) Many perl functions work implicitly on $_ if nothing else is stated.
3) one-line if are written in reverse. E.g.:
die if ($shot);

kev82 08-15-2003 12:19 PM

Quote:

The answers above are all very well, but doesn't fully solve the problem
<snip>
All fails to read in the file and to print out the result
but he asked
Quote:

could someone give a regex that detects a VALID ip address:
so your post doesnt answer the question either. dont try to be a smart ass, you normally just end up being an ass.

thanks for the perl hints though.


All times are GMT -5. The time now is 12:59 AM.