BitBonsai Labs Mauricio Wolff's geekness

29Jan/100

Python x PHP: Finding IPs with regex

Sometimes I just like to write code in Python and PHP to compare them, and admire both...

Here's a little code to find IP adressess inside strings (returned from a nslookup). The code is not optimal, but illustrate how both languages works. Just for some friday fun...

Python

 
Python 2.6.1 (r261:67515, Jul  7 2009,  23:51:51)
 [GCC 4.2.1 (Apple Inc. build 5646)] on darwin
 Type "help", "copyright", "credits" or "license"  for  more information.
 
>>> a  = 'yahoo.com IN A 69.147.114.224 18774s  (05:12:54)'
>>> a += 'yahoo.com IN A 209.131.36.159 18774s  (05:12:54)'
>>> a += 'yahoo.com IN A 209.191.93.53  18774s  (05:12:54)'
>>> print a
 'yahoo.com IN A 69.147.114.224  18774s (05:12:54)yahoo.com IN A 209.131.36.159 18774s  (05:12:54)yahoo.com IN A 209.191.93.53  18774s (05:12:54)'
>>>; import re
>>> p = re.compile('(?:\d{1,3}\.){3}\d{1,3}')
>>>; p.findall(a)
 ['69.147.114.224', '209.131.36.159',  '209.191.93.53']
>>>

PHP

$a  = 'yahoo.com IN A 69.147.114.224 18774s (05:12:54)';
$a .= 'yahoo.com  IN A 209.131.36.159 18774s (05:12:54)';
$a .= 'yahoo.com  IN A 209.191.93.53  18774s (05:12:54)';
 
print $a;
 
/*
saida: yahoo.com IN A 69.147.114.224 18774s (05:12:54)yahoo.com IN A  209.131.36.159 18774s (05:12:54)yahoo.com IN A 209.191.93.53 18774s  (05:12:54)
*/
 
$re = '/(\d+).(\d+).(\d+).(\d+)/';
 
preg_match_all($re, $a, $matches);
 
var_dump($matches[0]); // saida 1
var_dump($matches); // saida 2
 
/*
saida 1:
 
array(3) {
  [0]=>
  string(14) "69.147.114.224"
  [1]=>
  string(14) "209.131.36.159"
  [2]=>
  string(13) "209.191.93.53"
}
 
saida 2:
 
array(5) {
  [0]=>
  array(3) {
    [0]=>
    string(14) "69.147.114.224"
    [1]=>
    string(14) "209.131.36.159"
    [2]=>
    string(13) "209.191.93.53"
  }
  [1]=>
  array(3) {
    [0]=>
    string(2) "69"
    [1]=>
    string(3) "209"
    [2]=>
    string(3) "209"
  }
  [2]=>
  array(3) {
    [0]=>
    string(3) "147"
    [1]=>
    string(3) "131"
    [2]=>
    string(3) "191"
  }
  [3]=>
  array(3) {
    [0]=>
    string(3) "114"
    [1]=>
    string(2) "36"
    [2]=>
    string(2) "93"
  }
  [4]=>
  array(3) {
    [0]=>
    string(3) "224"
    [1]=>
    string(3) "159"
    [2]=>
    string(2) "53"
  }
}
*/
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.