nginx_upstream_hash-0.3.tar.gz http://wiki.codemongers.com/NginxHttpUpstreamRequestHa...
[nginx.git] / nginx / contrib / geo2nginx.pl
1 #!/usr/bin/perl -w\r
2 \r
3 # (c) Andrei Nigmatulin, 2005\r
4 #\r
5 # this script provided "as is", without any warranties. use it at your own risk.\r
6 #\r
7 # special thanx to Andrew Sitnikov for perl port\r
8 #\r
9 # this script converts CSV geoip database (free download at http://www.maxmind.com/app/geoip_country)\r
10 # to format, suitable for use with nginx_http_geo module (http://sysoev.ru/nginx)\r
11 #\r
12 # for example, line with ip range\r
13 #\r
14 #   "62.16.68.0","62.16.127.255","1041253376","1041268735","RU","Russian Federation"\r
15 #\r
16 # will be converted to four subnetworks:\r
17 #\r
18 #   62.16.68.0/22 RU;\r
19 #   62.16.72.0/21 RU;\r
20 #   62.16.80.0/20 RU;\r
21 #   62.16.96.0/19 RU;\r
22 \r
23 \r
24 use warnings;\r
25 use strict;\r
26 \r
27 while( <STDIN> ){\r
28         if (/"[^"]+","[^"]+","([^"]+)","([^"]+)","([^"]+)"/){\r
29                 print_subnets($1, $2, $3);\r
30         }\r
31 }\r
32 \r
33 sub  print_subnets {\r
34         my ($a1, $a2, $c) = @_;\r
35         my $l;\r
36     while ($a1 <= $a2) {\r
37                 for ($l = 0; ($a1 & (1 << $l)) == 0 && ($a1 + ((1 << ($l + 1)) - 1)) <= $a2; $l++){};\r
38                 print long2ip($a1) . "/" . (32 - $l) . " " . $c . ";\n";\r
39         $a1 += (1 << $l);\r
40         }\r
41 }\r
42 \r
43 sub long2ip {\r
44         my $ip = shift;\r
45 \r
46         my $str = 0;\r
47 \r
48         $str = ($ip & 255);\r
49 \r
50         $ip >>= 8;\r
51         $str = ($ip & 255).".$str";\r
52 \r
53         $ip >>= 8;\r
54         $str = ($ip & 255).".$str";\r
55 \r
56         $ip >>= 8;\r
57         $str = ($ip & 255).".$str";\r
58 }\r