Next: , Previous: , Up: Library   [Contents][Index]

5.25 Geolocation functions

The geolocation functions allow you to identify the country where the given IP address or host name is located. These functions are available only if the libmaxminddb library is installed and mailfromd is compiled with the ‘GeoIP2’ support.

The libmaxminddb library is distributed by ‘MaxMind’ under the terms of the Apache License Version 2.0. It is available from

Built-in Function: void geoip2_open (string filename)

Opens the geolocation database file filename. The database must be in GeoIP2 format.

If the database cannot be opened, geoip2_open throws the e_failure exception.

If this function is not called, geolocation functions described below will try to open the database file ‘/usr/share/GeoIP/GeoLite2-City.mmdb’.

Built-in Function: string geoip2_dbname (void)

Returns the name of the geolocation database currently in use.

The geolocation database for each IP address, which serves as a look up key, stores a set of items describing this IP. This set is organized as a map of key-value pairs. Each key is a string value. A value can be a scalar, another map or array of values. Using JSON notation, the result of a look up in the database might look as:

            "en": "Germany",
            "de": "Deutschland",

Each particular data item in such structure is identified by its search path, which is a dot-delimited list of key names leading to that value. For example, using the above map, the name of the city in English can be retrieved using the key city.names.en.

Built-in Function: string geoip2_get (string ip, string path)

Looks up the IP address ip in the geolocation database. If found, returns data item identified by the search path path.

The function can throw the following exceptions:


The ip was not found in the database.


The path does not exist the returned map.


General error occurred. E.g. the database cannot be opened, ip is not a valid IP address, etc.

Built-in Function: string geoip2_get_json (string ip [; number indent)

Looks up the ip in the database and returns entire data set associated with it, formatted as a JSON object. If the optional parameter indent is supplied and is greater than zero, it gives the indentation for each nesting level in the JSON object.

Applications may test whether the GeoIP2 support is present and enable the corresponding code blocks conditionally, by testing if the ‘WITH_GEOIP2’ m4 macro is defined. For example, the following code adds to the message the ‘X-Originator-Country’ header, containing the 2 letter code of the country where the client machine is located. If mailfromd is compiled without the ‘GeoIP2’ support, it does nothing:

    header_add("X-Originator-Country", geoip2_get($client_addr,
  catch e_not_found or e_range

Next: , Previous: , Up: Library   [Contents][Index]