Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5694944
  • 博文数量: 675
  • 博客积分: 20301
  • 博客等级: 上将
  • 技术积分: 7671
  • 用 户 组: 普通用户
  • 注册时间: 2005-12-31 16:15
文章分类

全部博文(675)

文章存档

2012年(1)

2011年(20)

2010年(14)

2009年(63)

2008年(118)

2007年(141)

2006年(318)

分类: C/C++

2010-05-24 15:54:20

最近要开始写毕业论文,开始处理一些程序的日志。网络程序日志中,网络四元组是很常见的,在P2P网络中,经常要对IP地址的地理位置进行统计。之前,写过使用纯真IP数据库的程序,但是感觉不太正式,在翻看一些p2p开源软件的代码的时候发现了GeoIP.c,就google了一下,发现了GeoIP这个开源项目。

GeoIP有很多的数据库,主要有Country、City、Org等ip地址对应的信息。

接口非常的方便,以常用的Country查询为例。结果有三种:2字节Country Code,3字节Country Code,不定长Country Code。

char *GeoIP_country_code_by_name(GeoIP* gi, char *name);
char *GeoIP_country_code_by_addr(GeoIP* gi, char *addr);
char *GeoIP_country_code3_by_name(GeoIP* gi, char *name);
char *GeoIP_country_code3_by_addr(GeoIP* gi, char *addr);
char *GeoIP_country_code_by_ipnum(GeoIP* gi, char *ipnum);
char *GeoIP_country_name_by_ipnum(GeoIP* gi, char *ipnum);

注意:
GeoIP_country_xxx_by_name()中的name,可以为域名、ip地址字符串;
GeoIP_country_xxx_by_addr()中的addr,为ip地址字符串;
GeoIP_country_xxx_by_ipnum()中ipnum,为ip地址主机字节序。


示例代码:

#include

#define DATAFILE "/home/wangyao/GeoIP.dat"

int main ()
{
  //char ipAddress[30]={0};
  char *ipAddress = "202.118.224.241";
  //char *ipAddress = "4.2.2.1";
  const char * returnedCountry = NULL;
  GeoIP * gi = NULL;

  /* Read from filesystem, check for updated file */
  //gi = GeoIP_open(DATAFILE, GEOIP_STANDARD | GEOIP_CHECK_CACHE);
  /* Read from memory, faster but takes up more memory */
  gi = GeoIP_open(DATAFILE, GEOIP_MEMORY_CACHE);

  if (gi == NULL) 
  {
      fprintf(stderr, "Error opening database\n");
      exit(1);
  }

  returnedCountry = GeoIP_country_code_by_name(gi, ipAddress);
  printf("%s: %s\n", ipAddress, returnedCountry);

  returnedCountry = GeoIP_country_code_by_addr(gi, ipAddress);
  printf("%s: %s\n", ipAddress, returnedCountry);

  returnedCountry = GeoIP_country_code3_by_addr(gi, ipAddress);
  printf("%s: %s\n", ipAddress, returnedCountry);

  returnedCountry = GeoIP_country_name_by_addr(gi, ipAddress);
  printf("%s: %s\n", ipAddress, returnedCountry);

  struct in_addr addr;
  inet_aton(ipAddress, &addr);
  returnedCountry = GeoIP_country_code_by_ipnum(gi, ntohl(addr.s_addr) );
  printf("%s: %s\n", ipAddress, returnedCountry);

  returnedCountry = GeoIP_country_name_by_ipnum(gi, ntohl(addr.s_addr) );
  printf("%s: %s\n", ipAddress, returnedCountry);

  GeoIP_delete(gi);
  return 0;
}

阅读(14116) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~