LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 08-12-2003, 04:34 AM   #1
Robert0380
LQ Guru
 
Registered: Apr 2002
Location: Atlanta
Distribution: Gentoo
Posts: 1,280

Rep: Reputation: 47
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.
 
Old 08-12-2003, 09:03 AM   #2
tjm
Member
 
Registered: Oct 2002
Posts: 55

Rep: Reputation: 15
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
 
Old 08-12-2003, 10:40 PM   #3
Robert0380
LQ Guru
 
Registered: Apr 2002
Location: Atlanta
Distribution: Gentoo
Posts: 1,280

Original Poster
Rep: Reputation: 47
perl...so cryptic looking, i dont know any perl but thanks.
 
Old 08-12-2003, 10:42 PM   #4
Robert0380
LQ Guru
 
Registered: Apr 2002
Location: Atlanta
Distribution: Gentoo
Posts: 1,280

Original Poster
Rep: Reputation: 47
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.
 
Old 08-12-2003, 11:17 PM   #5
Strike
Member
 
Registered: Jun 2001
Location: Houston, TX, USA
Distribution: Debian
Posts: 569

Rep: Reputation: 31
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
 
Old 08-13-2003, 03:41 PM   #6
Hko
Senior Member
 
Registered: Aug 2002
Location: Groningen, The Netherlands
Distribution: Debian
Posts: 2,536

Rep: Reputation: 111Reputation: 111
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.
 
Old 08-13-2003, 06:58 PM   #7
devoyage
Member
 
Registered: Aug 2003
Distribution: many
Posts: 37

Rep: Reputation: 15
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';}
 
Old 08-14-2003, 02:51 AM   #8
Strike
Member
 
Registered: Jun 2001
Location: Houston, TX, USA
Distribution: Debian
Posts: 569

Rep: Reputation: 31
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
 
Old 08-14-2003, 06:41 PM   #9
Robert0380
LQ Guru
 
Registered: Apr 2002
Location: Atlanta
Distribution: Gentoo
Posts: 1,280

Original Poster
Rep: Reputation: 47
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).

Last edited by Robert0380; 08-14-2003 at 06:42 PM.
 
Old 08-14-2003, 08:54 PM   #10
sk8guitar
Member
 
Registered: Jul 2003
Location: DC
Distribution: mandrake 9.1
Posts: 415

Rep: Reputation: 30
perl will do it great. the example posted was correct
 
Old 08-14-2003, 10:45 PM   #11
Robert0380
LQ Guru
 
Registered: Apr 2002
Location: Atlanta
Distribution: Gentoo
Posts: 1,280

Original Poster
Rep: Reputation: 47
the egrep one works also by the way....so that's atleast 2 that have been tested.
 
Old 08-15-2003, 04:23 AM   #12
kev82
Senior Member
 
Registered: Apr 2003
Location: Lancaster, England
Distribution: Debian Etch, OS X 10.4
Posts: 1,263

Rep: Reputation: 51
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.

Last edited by kev82; 08-15-2003 at 04:27 AM.
 
Old 08-15-2003, 09:52 AM   #13
Strike
Member
 
Registered: Jun 2001
Location: Houston, TX, USA
Distribution: Debian
Posts: 569

Rep: Reputation: 31
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.


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
 
Old 08-15-2003, 11:54 AM   #14
esben
Member
 
Registered: Jun 2003
Location: Copenhagen, Denmark
Distribution: Gentoo
Posts: 48

Rep: Reputation: 15
Lightbulb Re: ip address REGEX

The answers above are all very well, but doesn't fully solve the problem

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 (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);
 
Old 08-15-2003, 12:19 PM   #15
kev82
Senior Member
 
Registered: Apr 2003
Location: Lancaster, England
Distribution: Debian Etch, OS X 10.4
Posts: 1,263

Rep: Reputation: 51
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.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
regex Perl help igotlongestname Programming 2 09-14-2005 07:51 PM
regex in paths basher400 Linux - Newbie 3 06-15-2005 07:08 AM
Regex Help cmfarley19 Programming 5 03-31-2005 10:13 PM
how to get ip address, broadcast address, mac address of a machine sumeshstar Programming 2 03-12-2005 04:33 AM
Help with Sed and regex cmfarley19 Programming 6 11-18-2004 01:09 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 05:44 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration