geo2nginx.pl 1.2 KB

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