• Stars
    star
    348
  • Rank 121,840 (Top 3 %)
  • Language
    C#
  • License
    Apache License 2.0
  • Created about 11 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

MaxMind GeoIP2 .NET API

GeoIP2 .NET API

NuGet API Docs

Description

This distribution provides an API for the GeoIP2 and GeoLite2 web services and databases.

Installation

NuGet

We recommend installing this library with NuGet. To do this, type the following into the Visual Studio Package Manager Console:

install-package MaxMind.GeoIP2

IP Geolocation Usage

IP geolocation is inherently imprecise. Locations are often near the center of the population. Any location provided by a GeoIP2 database or web service should not be used to identify a particular address or household.

Web Service Usage

To use the web service API, first create a new WebServiceClient object with your account ID and license key:

var client = new WebServiceClient(42, "license_key1");

To query the GeoLite2 web service, you must set the host to geolite.info:

var client = new WebServiceClient(42, "license_key1", host: "geolite.info");

You may also specify the fall-back locales, the host, or the timeout as optional parameters. See the API docs for more information.

This object is safe to share across threads. If you are making multiple requests, the object should be reused to so that new connections are not created for each request. Once you have finished making requests, you should dispose of the object to ensure the connections are closed and any resources are promptly returned to the system.

You may then call the sync or async method corresponding to the specific end point, passing it the IP address you want to look up or no parameters if you want to look up the current device.

If the request succeeds, the method call will return a response class for the endpoint you called. This response in turn contains multiple model classes, each of which represents part of the data returned by the web service.

See the API documentation for more details.

ASP.NET Core Usage

To use the web service API with HttpClient factory pattern as a Typed client you need to do the following:

  1. Add the following lines to Startup.cs ConfigureServices method:
// Configure to read configuration options from MaxMind section
services.Configure<WebServiceClientOptions>(Configuration.GetSection("MaxMind"));

// Configure dependency injection for WebServiceClient
services.AddHttpClient<WebServiceClient>();
  1. Add configuration in your appsettings.json with your account ID and license key.
...
  "MaxMind": {
    "AccountId": 123456,
    "LicenseKey": "1234567890",

    // Optionally set a timeout. The default is 3000 ms.
    // "Timeout": 3000,

    // Optionally set host. "geolite.info" will use the GeoLite2
    // web service instead of GeoIP2.
    //
    // "Host": "geolite.info"
  },
...
  1. Inject the WebServiceClient where you need to make the call and use it.
[ApiController]
[Route("[controller]")]
public class MaxMindController : ControllerBase
{
    private readonly WebServiceClient _maxMindClient;

    public MaxMindController(WebServiceClient maxMindClient)
    {
        _maxMindClient = maxMindClient;
    }

    [HttpGet]
    public async Task<string> Get()
    {
        var location = await _maxMindClient.CountryAsync();

        return location.Country.Name;
    }
}

Web Service Example

Country Service (Sync)

// If you are making multiple requests, a single WebServiceClient
// should be shared across requests to allow connection reuse. The
// class is thread safe.
//
// Replace "42" with your account ID and "license_key" with your license
// key. Set the named host argument to "geolite.info" to use the GeoLite2
// web service instead of GeoIP2.
using (var client = new WebServiceClient(42, "license_key"))
{
    // Do the lookup
    var response = client.Country("128.101.101.101");

    Console.WriteLine(response.Country.IsoCode);        // 'US'
    Console.WriteLine(response.Country.Name);           // 'United States'
    Console.WriteLine(response.Country.Names["zh-CN"]); // '美国'
}

Country Service (Async)

// If you are making multiple requests, a single WebServiceClient
// should be shared across requests to allow connection reuse. The
// class is thread safe.
//
// Replace "42" with your account ID and "license_key" with your license
// key. Set the named host argument to "geolite.info" to use the GeoLite2
// web service instead of GeoIP2.
using (var client = new WebServiceClient(42, "license_key"))
{
    // Do the lookup
    var response = await client.CountryAsync("128.101.101.101");

    Console.WriteLine(response.Country.IsoCode);        // 'US'
    Console.WriteLine(response.Country.Name);           // 'United States'
    Console.WriteLine(response.Country.Names["zh-CN"]); // '美国'
}

City Plus Service (Sync)

// If you are making multiple requests, a single WebServiceClient
// should be shared across requests to allow connection reuse. The
// class is thread safe.
//
// Replace "42" with your account ID and "license_key" with your license
// key. Set the named host argument to "geolite.info" to use the GeoLite2
// web service instead of GeoIP2.
using (var client = new WebServiceClient(42, "license_key"))
{
    // Do the lookup
    var response = client.City("128.101.101.101");

    Console.WriteLine(response.Country.IsoCode);        // 'US'
    Console.WriteLine(response.Country.Name);           // 'United States'
    Console.WriteLine(response.Country.Names["zh-CN"]); // '美国'

    Console.WriteLine(response.MostSpecificSubdivision.Name);    // 'Minnesota'
    Console.WriteLine(response.MostSpecificSubdivision.IsoCode); // 'MN'

    Console.WriteLine(response.City.Name); // 'Minneapolis'

    Console.WriteLine(response.Postal.Code); // '55455'

    Console.WriteLine(response.Location.Latitude);  // 44.9733
    Console.WriteLine(response.Location.Longitude); // -93.2323
}

City Plus Service (Async)

// If you are making multiple requests, a single WebServiceClient
// should be shared across requests to allow connection reuse. The
// class is thread safe.
//
// Replace "42" with your account ID and "license_key" with your license
// key. Set the named host argument to "geolite.info" to use the GeoLite2
// web service instead of GeoIP2.
using (var client = new WebServiceClient(42, "license_key"))
{
    // Do the lookup
    var response = await client.CityAsync("128.101.101.101");

    Console.WriteLine(response.Country.IsoCode);        // 'US'
    Console.WriteLine(response.Country.Name);           // 'United States'
    Console.WriteLine(response.Country.Names["zh-CN"]); // '美国'

    Console.WriteLine(response.MostSpecificSubdivision.Name);    // 'Minnesota'
    Console.WriteLine(response.MostSpecificSubdivision.IsoCode); // 'MN'

    Console.WriteLine(response.City.Name); // 'Minneapolis'

    Console.WriteLine(response.Postal.Code); // '55455'

    Console.WriteLine(response.Location.Latitude);  // 44.9733
    Console.WriteLine(response.Location.Longitude); // -93.2323
}

Insights Service (Sync)

// If you are making multiple requests, a single WebServiceClient
// should be shared across requests to allow connection reuse. The
// class is thread safe.
//
// Replace "42" with your account ID and "license_key" with your license
// key. The GeoLite2 web service does not support Insights.
using (var client = new WebServiceClient(42, "license_key"))
{
    // Do the lookup
    var response = client.Insights("128.101.101.101");

    Console.WriteLine(response.Country.IsoCode);        // 'US'
    Console.WriteLine(response.Country.Name);           // 'United States'
    Console.WriteLine(response.Country.Names["zh-CN"]); // '美国'

    Console.WriteLine(response.MostSpecificSubdivision.Name);    // 'Minnesota'
    Console.WriteLine(response.MostSpecificSubdivision.IsoCode); // 'MN'

    Console.WriteLine(response.City.Name); // 'Minneapolis'

    Console.WriteLine(response.Postal.Code); // '55455'

    Console.WriteLine(response.Location.Latitude);  // 44.9733
    Console.WriteLine(response.Location.Longitude); // -93.2323
}

Insights Service (Async)

// If you are making multiple requests, a single WebServiceClient
// should be shared across requests to allow connection reuse. The
// class is thread safe.
//
// Replace "42" with your account ID and "license_key" with your license
// key. The GeoLite2 web service does not support Insights.
using (var client = new WebServiceClient(42, "license_key"))
{
    // Do the lookup
    var response = await client.InsightsAsync("128.101.101.101");

    Console.WriteLine(response.Country.IsoCode);        // 'US'
    Console.WriteLine(response.Country.Name);           // 'United States'
    Console.WriteLine(response.Country.Names["zh-CN"]); // '美国'

    Console.WriteLine(response.MostSpecificSubdivision.Name);    // 'Minnesota'
    Console.WriteLine(response.MostSpecificSubdivision.IsoCode); // 'MN'

    Console.WriteLine(response.City.Name); // 'Minneapolis'

    Console.WriteLine(response.Postal.Code); // '55455'

    Console.WriteLine(response.Location.Latitude);  // 44.9733
    Console.WriteLine(response.Location.Longitude); // -93.2323
}

Database Usage

To use the database API, you must create a new DatabaseReader with a string representation of the path to your GeoIP2 database. You may also specify the file access mode. You may then call the appropriate method (e.g., city) for your database, passing it the IP address you want to look up.

If the lookup succeeds, the method call will return a response class for the GeoIP2 lookup. This class in turn contains multiple model classes, each of which represents part of the data returned by the database.

We recommend reusing the DatabaseReader object rather than creating a new one for each lookup. The creation of this object is relatively expensive as it must read in metadata for the file.

See the API documentation for more details.

Database Examples

Anonymous IP Database

using (var reader = new DatabaseReader("GeoIP2-Anonymous-IP.mmdb"))
{
    var response = reader.AnonymousIP("85.25.43.84");
    Console.WriteLine(response.IsAnonymous);        // true
    Console.WriteLine(response.IsAnonymousVpn);     // false
    Console.WriteLine(response.IsHostingProvider);  // false
    Console.WriteLine(response.IsPublicProxy);      // false
    Console.WriteLine(response.IsResidentialProxy); // false
    Console.WriteLine(response.IsTorExitNode);      // true
    Console.WriteLine(response.IPAddress);          // '85.25.43.84'
}

ASN

using (var reader = new DatabaseReader("GeoLite2-ASN.mmdb"))
{
    var response = reader.Asn("85.25.43.84");
    Console.WriteLine(response.AutonomousSystemNumber); // 217
    Console.WriteLine(response.AutonomousSystemOrganization); // 'University of Minnesota'
    Console.WriteLine(response.IPAddress); // '128.101.101.101'
}

City Database

// This creates the DatabaseReader object, which should be reused across
// lookups.
using (var reader = new DatabaseReader("GeoIP2-City.mmdb"))
{
    // Replace "City" with the appropriate method for your database, e.g.,
    // "Country".
    var city = reader.City("128.101.101.101");

    Console.WriteLine(city.Country.IsoCode); // 'US'
    Console.WriteLine(city.Country.Name); // 'United States'
    Console.WriteLine(city.Country.Names["zh-CN"]); // '美国'

    Console.WriteLine(city.MostSpecificSubdivision.Name); // 'Minnesota'
    Console.WriteLine(city.MostSpecificSubdivision.IsoCode); // 'MN'

    Console.WriteLine(city.City.Name); // 'Minneapolis'

    Console.WriteLine(city.Postal.Code); // '55455'

    Console.WriteLine(city.Location.Latitude); // 44.9733
    Console.WriteLine(city.Location.Longitude); // -93.2323
}

Connection-Type Database

using (var reader = new DatabaseReader("GeoIP2-Connection-Type.mmdb"))
{
    var response = reader.ConnectionType("128.101.101.101");
    Console.WriteLine(response.ConnectionType); // 'Corporate'
    Console.WriteLine(response.IPAddress); // '128.101.101.101'
}

Domain Database

using (var reader = new DatabaseReader("GeoIP2-Domain.mmdb"))
{
    var response = reader.Domain("128.101.101.101");
    Console.WriteLine(response.Domain); // 'umn.edu'
    Console.WriteLine(response.IPAddress); // '128.101.101.101'
}

Enterprise Database

using (var reader = new DatabaseReader("/path/to/GeoIP2-Enterprise.mmdb"))
{
    //  Use the Enterprise(ip) method to do a lookup in the Enterprise database
    var response = reader.enterprise("128.101.101.101");

    var country = response.Country;
    Console.WriteLine(country.IsoCode);            // 'US'
    Console.WriteLine(country.Name);               // 'United States'
    Console.WriteLine(country.Names["zh-CN"]);     // '美国'
    Console.WriteLine(country.Confidence);         // 99

    var subdivision = response.MostSpecificSubdivision;
    Console.WriteLine(subdivision.Name);           // 'Minnesota'
    Console.WriteLine(subdivision.IsoCode);        // 'MN'
    Console.WriteLine(subdivision.Confidence);     // 77

    var city = response.City;
    Console.WriteLine(city.Name);       // 'Minneapolis'
    Console.WriteLine(city.Confidence); // 11

    var postal = response.Postal;
    Console.WriteLine(postal.Code); // '55455'
    Console.WriteLine(postal.Confidence); // 5

    var location = response.Location;
    Console.WriteLine(location.Latitude);       // 44.9733
    Console.WriteLine(location.Longitude);      // -93.2323
    Console.WriteLine(location.AccuracyRadius); // 50
}

ISP Database

using (var reader = new DatabaseReader("GeoIP2-ISP.mmdb"))
{
    var response = reader.Isp("128.101.101.101");
    Console.WriteLine(response.AutonomousSystemNumber); // 217
    Console.WriteLine(response.AutonomousSystemOrganization); // 'University of Minnesota'
    Console.WriteLine(response.Isp); // 'University of Minnesota'
    Console.WriteLine(response.Organization); // 'University of Minnesota'
    Console.WriteLine(response.IPAddress); // '128.101.101.101'
}

Exceptions

Database

If the database is corrupt or otherwise invalid, a MaxMind.Db.InvalidDatabaseException will be thrown.

If an address is not available in the database, a AddressNotFoundException will be thrown.

Web Service

For details on the possible errors returned by the web service itself, see the GeoIP2 web service documentation.

If the web service returns an explicit error document, this is thrown as a AddressNotFoundException, a AuthenticationException, a InvalidRequestException, or a OutOfQueriesException.

If some sort of transport error occurs, an HttpException is thrown. This is thrown when some sort of unanticipated error occurs, such as the web service returning a 500 or an invalid error document. If the web service request returns any status code besides 200, 4xx, or 5xx, this also becomes a HttpException.

Finally, if the web service returns a 200 but the body is invalid, the client throws a GeoIP2Exception. This exception also is the parent exception to the above exceptions.

Values to use for Database or Dictionary Keys

We strongly discourage you from using a value from any Names property as a key in a database or dictionary.

These names may change between releases. Instead we recommend using one of the following:

  • MaxMind.GeoIP2.Model.City - City.GeoNameId
  • MaxMind.GeoIP2.Model.Continent - Continent.Code or Continent.GeoNameId
  • MaxMind.GeoIP2.Model.Country and MaxMind.GeoIP2.Model.RepresentedCountry
    • Country.IsoCode or Country.GeoNameId
  • MaxMind.GeoIP2.Model.Subdivision - Subdivision.IsoCode or Subdivision.GeoNameId

Multi-Threaded Use

This API fully supports use in multi-threaded applications. When using the DatabaseReader in a multi-threaded application, we suggest creating one object and sharing that among threads.

What data is returned?

While many of the end points return the same basic records, the attributes which can be populated vary between end points. In addition, while an end point may offer a particular piece of data, MaxMind does not always have every piece of data for any given IP address.

Because of these factors, it is possible for any end point to return a record where some or all of the attributes are unpopulated.

See the GeoIP2 web services documentations for details on what data each end point may return.

The only piece of data which is always returned is the ipAddress attribute in the MaxMind.GeoIP2.Traits record.

Integration with GeoNames

GeoNames offers web services and downloadable databases with data on geographical features around the world, including populated places. They offer both free and paid premium data. Each feature is unique identified by a geonameId, which is an integer.

Many of the records returned by the GeoIP2 web services and databases include a geonameId property. This is the ID of a geographical feature (city, region, country, etc.) in the GeoNames database.

Some of the data that MaxMind provides is also sourced from GeoNames. We source things like place names, ISO codes, and other similar data from the GeoNames premium data set.

Reporting data problems

If the problem you find is that an IP address is incorrectly mapped, please submit your correction to MaxMind.

If you find some other sort of mistake, like an incorrect spelling, please check the GeoNames site first. Once you've searched for a place and found it on the GeoNames map view, there are a number of links you can use to correct data ("move", "edit", "alternate names", etc.). Once the correction is part of the GeoNames data set, it will be automatically incorporated into future MaxMind releases.

If you are a paying MaxMind customer and you're not sure where to submit a correction, please contact MaxMind support for help.

Other Support

Please report all issues with this code using the GitHub issue tracker.

If you are having an issue with a MaxMind service that is not specific to the client API, please see our support page.

Contributing

Patches and pull requests are encouraged. Please include unit tests whenever possible.

Versioning

The API uses Semantic Versioning. However, adding new methods to IGeoIP2Provider, IGeoIP2DatabaseReader, and IGeoIP2WebServicesClient will not be considered a breaking change. These interfaces only exist to facilitate unit testing and dependency injection. They will be updated to match additional methods added to the DatabaseReader and WebServiceClient. Such additions will be accompanied by a minor version bump (e.g., 1.2.x to 1.3.0).

Copyright and License

This software is Copyright (c) 2013-2022 by MaxMind, Inc.

This is free software, licensed under the Apache License, Version 2.0.

More Repositories

1

GeoIP2-php

PHP API for GeoIP2 webservice client and database reader
PHP
2,325
star
2

GeoIP2-python

Python code for GeoIP2 webservice client and database reader
Python
1,107
star
3

libmaxminddb

C library for the MaxMind DB file format
C
913
star
4

GeoIP2-java

Java API for GeoIP2 webservice client and database reader
Java
781
star
5

geoipupdate

GeoIP update client code
Go
723
star
6

MaxMind-DB-Reader-php

PHP Reader for the MaxMind DB Database Format
PHP
639
star
7

geoip-api-php

DEPRECATED GeoIP Legacy PHP API
PHP
523
star
8

geoip-api-c

DEPRECATED GeoIP Legacy C API
C
371
star
9

web-service-common-php

Shared code for the MaxMind Web Service PHP client APIs
PHP
288
star
10

MaxMind-DB

Spec and test data for the MaxMind DB file format
Go
277
star
11

geoipupdate-legacy

GeoIP update client code
C
258
star
12

geoip-api-python

DEPRECATED GeoIP Legacy Python API
C
232
star
13

GeoIP2-node

Node.js API for GeoIP2 webservice client and database reader
TypeScript
223
star
14

geoip2-csv-converter

GeoIP2 CSV Format Converter
Go
202
star
15

MaxMind-DB-Reader-python

Python MaxMind DB reader extension
Python
178
star
16

geoip-api-java

DEPRECATED GeoIP Legacy Java API
Java
176
star
17

mmdbinspect

look up records for one or more IPs/networks in one or more .mmdb databases
Go
130
star
18

mod_maxminddb

MaxMind DB Apache Module
C
126
star
19

MaxMind-DB-Reader-java

Java reader for the MaxMind DB format
Java
114
star
20

mmdbwriter

Go library for writing MaxMind DB (mmdb) files
Go
114
star
21

MaxMind-DB-Reader-dotnet

.NET Reader for the MaxMind DB Database Format
C#
102
star
22

MaxMind-DB-Writer-perl

Create MaxMind DB database files
Perl
75
star
23

GeoIP2-ruby

Ruby API for GeoIP2 webservice client and database reader
Ruby
59
star
24

geoip-api-mod_geoip2

DEPRECATED GeoIP Legacy module for Apache 2
C
50
star
25

minfraud-api-php

PHP API for minFraud Score, Insights, and Factors
PHP
49
star
26

geoip-api-csharp2

DEPRECATED GeoIP Legacy C# API
C#
47
star
27

MaxMind-DB-Reader-ruby

Ruby reader for the MaxMind DB Database Format
Ruby
46
star
28

getting-started-with-mmdb

A quick guide to writing and reading from your own MMDB databases.
Perl
37
star
29

minfraud-api-python

Python API for minFraud Score, Insights, and Factors
Python
27
star
30

mmdb-from-go-blogpost

Enriching MMDB files with your own data using Go.
Go
23
star
31

ccfd-api-php

Deprecated minFraud Legacy PHP API
PHP
23
star
32

minfraud-api-dotnet

.NET API for MaxMind minFraud Score, Insights, and Factors
C#
20
star
33

minfraud-api-java

Java API for minFraud Score, Insights, and Factors
Java
19
star
34

GeoIP2-perl

Perl API for MaxMind's GeoIP2 web services and databases
Perl
18
star
35

mm-geofeed-verifier

Verify the format of a geofeed file, and make some comparisons to data in an MMDB file.
Go
16
star
36

minfraud-api-ruby

Ruby API for minFraud Score, Insights, and Factors
Ruby
14
star
37

minfraud-api-node

Node.js API for MaxMind minFraud Score, Insights, and Factors
TypeScript
14
star
38

mm-network-analyzer

A program to aid in diagnosing networking issues
Go
13
star
39

dev-hire-homework

A homework exercise for engineering applicants
Perl
13
star
40

MaxMind-DB-Reader-perl

Read MaxMind DB files and look up IP addresses
Perl
12
star
41

mmdbverify

Verifier for the MaxMind DB format
Go
10
star
42

geoip-api-perl

DEPRECATED GeoIP Legacy Perl API
Perl
10
star
43

Stepford

A vaguely Rake/Make/Cake-like thing for Perl - create steps and let a runner run them
Perl
9
star
44

ccfd-api-java

Deprecated minFraud Legacy Java API
Java
7
star
45

Locale-Country-Multilingual

mapping ISO codes to localized country names
Perl
6
star
46

Database-Migrator

Mirror of Database-Migrator on urth.org
Perl
5
star
47

Net-Works

Sane APIs for IP addresses and networks
Perl
5
star
48

MaxMind-DB-Reader-XS

Fast XS implementation of MaxMind DB reader
Perl
5
star
49

dev-site

Static site generator for https://dev.maxmind.com.
HTML
4
star
50

xgb2code

A converter for xgboost model dumps to code.
Go
4
star
51

ccfd-api-asp

minFraud ASP API
ASP
3
star
52

webservice-paypal-paymentsadvanced

A simple wrapper around the PayPal Payments Advanced web service
Perl
3
star
53

gatling-gen

C++
2
star
54

geoip-api-mscom

DEPRECATED GeoIP Legacy MS COM API
C
2
star
55

App-CISetup

Command line tools to generate and update Travis and AppVeyor configs for Perl libraries
Perl
2
star
56

api-specs

TypeScript
2
star
57

MaxMind-DB-Common-perl

Code shared by the MaxMind DB reader and writer modules
Perl
2
star
58

WebService-PivotalTracker

Perl library for the Pivotal Tracker REST API
Perl
2
star
59

minfraud-api-perl

Perl API for minFraud Score, Insights, and Factors
Perl
2
star
60

TAP-Formatter-TeamCity

Emit test results as TeamCity build messages
Perl
2
star
61

geolite2-ws-blogpost

Integrating MaxMind's Free and Paid IP Geolocation Web Services (in PHP)
PHP
2
star
62

fuzzing-workshop

Code for Summit Fuzzing Workshop
Go
1
star
63

Dist-Zilla-PluginBundle-MAXMIND

Perl
1
star
64

blog-site

Static site generator for https://blog.maxmind.com.
SCSS
1
star
65

TeamCity-Message

Generate TeamCity build messages
Perl
1
star
66

xgbshap

Calculates feature contributions for XGBoost models
Go
1
star