Skip to content

Instantly share code, notes, and snippets.

@electrum
Created May 4, 2010 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save electrum/390022 to your computer and use it in GitHub Desktop.
Save electrum/390022 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <GeoIPCity.h>
int main(int argc, char *argv[])
{
GeoIP *geo;
char buf[32768];
char addr[16];
unsigned int ip1, ip2, ip3, ip4;
GeoIPRecord *rec;
geo = GeoIP_open_type(GEOIP_CITY_EDITION_REV1, GEOIP_MEMORY_CACHE);
if (geo == NULL)
{
fprintf(stderr, "Failed to open GeoIP city database\n");
return 100;
}
while (!feof(stdin))
{
if (fgets(buf, sizeof(buf), stdin) == NULL)
break;
if (sscanf(buf, "%u.%u.%u.%u", &ip1, &ip2, &ip3, &ip4) != 4)
continue;
if ((ip1 > 255) || (ip2 > 255) || (ip3 > 255) || (ip4 > 255))
continue;
snprintf(addr, sizeof(buf), "%u.%u.%u.%u", ip1, ip2, ip3, ip4);
rec = GeoIP_record_by_addr(geo, addr);
if (rec == NULL)
printf("%s\t??\t??\t??\t??\t??\t??\t??\t??\n", addr);
else
printf("%s\t%s\t%s\t%s\t%s\t%d\t%d\t%0.6f\t%0.6f\n", addr,
rec->country_code,
rec->region ? rec->region : "??",
rec->city ? rec->city : "??",
rec->postal_code ? rec->postal_code : "??",
rec->dma_code,
rec->area_code,
rec->latitude,
rec->longitude);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment