使用GeoIP获得IP地址的地理地址信息

最近要开始写毕业论文,开始处理一些程序的日志。网络程序日志中,网络四元组是很常见的,在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 <GeoIP.h>

#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;
}
转自:http://blog.chinaunix.net/uid-20357359-id-1963688.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值