Class: GeoIP

Inherits:
Object
  • Object
show all
Defined in:
lib/geoip.rb

Defined Under Namespace

Classes: ASN, City, Country, Region

Constant Summary collapse

VERSION =

The GeoIP GEM version number

"1.3.2"
DATA_DIR =

The data/ directory for geoip

File.expand_path(File.join(File.dirname(__FILE__),'..','data','geoip'))
CountryCode =

Ordered list of the ISO3166 2-character country codes, ordered by GeoIP ID

YAML.load_file(File.join(DATA_DIR,'country_code.yml'))
CountryCode3 =

Ordered list of the ISO3166 3-character country codes, ordered by GeoIP ID

YAML.load_file(File.join(DATA_DIR,'country_code3.yml'))
CountryName =

Ordered list of the English names of the countries, ordered by GeoIP ID

YAML.load_file(File.join(DATA_DIR,'country_name.yml'))
CountryContinent =

Ordered list of the ISO3166 2-character continent code of the countries, ordered by GeoIP ID

YAML.load_file(File.join(DATA_DIR,'country_continent.yml'))
RegionName =

Load a hash of region names by region code

YAML.load_file(File.join(DATA_DIR,'region.yml'))
TimeZone =

Hash of the timezone codes mapped to timezone name, per zoneinfo

YAML.load_file(File.join(DATA_DIR,'time_zone.yml'))
GEOIP_COUNTRY_EDITION =
1
GEOIP_CITY_EDITION_REV1 =
2
GEOIP_REGION_EDITION_REV1 =
3
GEOIP_ISP_EDITION =
4
GEOIP_ORG_EDITION =
5
GEOIP_CITY_EDITION_REV0 =
6
GEOIP_REGION_EDITION_REV0 =
7
GEOIP_PROXY_EDITION =
8
GEOIP_ASNUM_EDITION =
9
GEOIP_NETSPEED_EDITION =
10
GEOIP_COUNTRY_EDITION_V6 =
12
GEOIP_CITY_EDITION_REV1_V6 =
30
COUNTRY_BEGIN =

:nodoc:

16776960
STATE_BEGIN_REV0 =

:nodoc:

16700000
STATE_BEGIN_REV1 =

:nodoc:

16000000
STRUCTURE_INFO_MAX_SIZE =

:nodoc:

20
DATABASE_INFO_MAX_SIZE =

:nodoc:

100
MAX_ORG_RECORD_LENGTH =

:nodoc:

300
MAX_ASN_RECORD_LENGTH =

:nodoc: unverified

300
US_OFFSET =

:nodoc:

1
CANADA_OFFSET =

:nodoc:

677
WORLD_OFFSET =

:nodoc:

1353
FIPS_RANGE =

:nodoc:

360
FULL_RECORD_LENGTH =

:nodoc:

50
STANDARD_RECORD_LENGTH =

:nodoc:

3
SEGMENT_RECORD_LENGTH =

:nodoc:

3

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename, flags = 0) ⇒ GeoIP

Open the GeoIP database and determine the file format version.

filename is a String holding the path to the GeoIP.dat file options is an integer holding caching flags (unimplemented)



170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/geoip.rb', line 170

def initialize(filename, flags = 0)
  @mutex = unless IO.respond_to?(:pread)
             Mutex.new
           end

  @flags = flags
  @database_type = GEOIP_COUNTRY_EDITION
  @record_length = STANDARD_RECORD_LENGTH
  @file = File.open(filename, 'rb')

  detect_database_type!
end

Instance Attribute Details

#database_typeObject (readonly) Also known as: databaseType

The Edition number that identifies which kind of database you’ve opened



158
159
160
# File 'lib/geoip.rb', line 158

def database_type
  @database_type
end

#local_ip_aliasObject

An IP that is used instead of local IPs



161
162
163
# File 'lib/geoip.rb', line 161

def local_ip_alias
  @local_ip_alias
end

Instance Method Details

#asn(hostname) ⇒ Object

Search a ASN GeoIP database for the specified host, returning the AS number and description.

hostname is a String holding the host’s DNS name or numeric IP address.

Returns the AS number and description.

Source: geolite.maxmind.com/download/geoip/database/asnum/GeoIPASNum.dat.gz



364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
# File 'lib/geoip.rb', line 364

def asn(hostname)
  ip = lookup_ip(hostname)

  # Convert numeric IP address to an integer
  ipnum = iptonum(ip)

  if (@database_type != GEOIP_ASNUM_EDITION)
    throw "Invalid GeoIP database type, can't look up ASN by IP"
  end

  pos = seek_record(ipnum)
  off = pos + (2*@record_length - 1) * @database_segments[0]

  record = atomic_read(MAX_ASN_RECORD_LENGTH, off)
  record = record.sub(/\000.*/n, '')

  # AS####, Description
  ASN.new($1, $2) if record =~ /^(AS\d+)\s(.*)$/
end

#city(hostname) ⇒ Object

Search the GeoIP database for the specified host, returning city info.

hostname is a String holding the host’s DNS name or numeric IP address.

Returns a City object with the fourteen elements:

  • The host or IP address string as requested

  • The IP address string after looking up the host

  • The two-character country code (ISO 3166-1 alpha-2)

  • The three-character country code (ISO 3166-2 alpha-3)

  • The ISO 3166 English-language name of the country

  • The two-character continent code

  • The region name (state or territory)

  • The city name

  • The postal code (zipcode)

  • The latitude

  • The longitude

  • The USA dma_code if known (only REV1 City database)

  • The USA area_code if known (only REV1 City database)

  • The timezone name, if known



296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# File 'lib/geoip.rb', line 296

def city(hostname)
  ip = lookup_ip(hostname)

  if (@database_type == GEOIP_CITY_EDITION_REV0 ||
      @database_type == GEOIP_CITY_EDITION_REV1)
    # Convert numeric IP address to an integer
    ipnum = iptonum(ip)
    pos = seek_record(ipnum)
  elsif (@database_type == GEOIP_CITY_EDITION_REV1_V6)
    ipaddr = IPAddr.new ip
    pos = seek_record_v6(ipaddr.to_i)
  else
    throw "Invalid GeoIP database type, can't look up City by IP"
  end

  # This next statement was added to MaxMind's C version after it was
  # rewritten in Ruby. It prevents unassigned IP addresses from returning
  # bogus data.  There was concern over whether the changes to an
  # application's behaviour were always correct, but this has been tested
  # using an exhaustive search of the top 16 bits of the IP address space.
  # The records where the change takes effect contained *no* valid data. 
  # If you're concerned, email me, and I'll send you the test program so
  # you can test whatever IP range you think is causing problems,
  # as I don't care to undertake an exhaustive search of the 32-bit space.
  unless pos == @database_segments[0]
    read_city(pos, hostname, ip)
  end
end

#country(hostname) ⇒ Object

Search the GeoIP database for the specified host, returning country info.

hostname is a String holding the host’s DNS name or numeric IP address.

If the database is a City database (normal), return the result that city would return.

Otherwise, return a Country object with the seven elements:

  • The host or IP address string as requested

  • The IP address string after looking up the host

  • The GeoIP country-ID as an integer (N.B. this is excluded from the city results!)

  • The two-character country code (ISO 3166-1 alpha-2)

  • The three-character country code (ISO 3166-2 alpha-3)

  • The ISO 3166 English-language name of the country

  • The two-character continent code



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/geoip.rb', line 202

def country(hostname)
  if (@database_type == GEOIP_CITY_EDITION_REV0 ||
      @database_type == GEOIP_CITY_EDITION_REV1 ||
      @database_type == GEOIP_CITY_EDITION_REV1_V6)
    return city(hostname)
  end

  if (@database_type == GEOIP_REGION_EDITION_REV0 ||
      @database_type == GEOIP_REGION_EDITION_REV1)
    return region(hostname)
  end

  ip = lookup_ip(hostname)
  if (@database_type == GEOIP_COUNTRY_EDITION ||
      @database_type == GEOIP_PROXY_EDITION ||
      @database_type == GEOIP_NETSPEED_EDITION)
      # Convert numeric IP address to an integer
      ipnum = iptonum(ip)
      code = (seek_record(ipnum) - COUNTRY_BEGIN)
  elsif @database_type == GEOIP_COUNTRY_EDITION_V6
    ipaddr = IPAddr.new ip
    code = (seek_record_v6(ipaddr.to_i) - COUNTRY_BEGIN)
  else
    throw "Invalid GeoIP database type, can't look up Country by IP"
  end

  Country.new(
    hostname,                   # Requested hostname
    ip,                         # Ip address as dotted quad
    code,                       # GeoIP's country code
    CountryCode[code],          # ISO3166-1 alpha-2 code
    CountryCode3[code],         # ISO3166-2 alpha-3 code
    CountryName[code],          # Country name, per ISO 3166
    CountryContinent[code]      # Continent code.
  )
end

#eachObject

Iterate through a GeoIP city database



395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/geoip.rb', line 395

def each
  return enum_for unless block_given?

  if (@database_type != GEOIP_CITY_EDITION_REV0 &&
      @database_type != GEOIP_CITY_EDITION_REV1)
    throw "Invalid GeoIP database type, can't iterate thru non-City database"
  end

  @iter_pos = @database_segments[0] + 1
  num = 0

  until ((rec = read_city(@iter_pos)).nil?)
    yield rec
    print "#{num}: #{@iter_pos}\n" if((num += 1) % 1000 == 0)
  end

  @iter_pos = nil
  return self
end

#isp(hostname) ⇒ Object Also known as: organization

Search a ISP GeoIP database for the specified host, returning the ISP Not all GeoIP databases contain ISP information. Check maxmind.com

hostname is a String holding the host’s DNS name or numeric IP address.

Returns the ISP name.



334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/geoip.rb', line 334

def isp(hostname)
  ip = lookup_ip(hostname)

  # Convert numeric IP address to an integer
  ipnum = iptonum(ip)

  if (@database_type != GEOIP_ISP_EDITION &&
      @database_type != GEOIP_ORG_EDITION)
    throw "Invalid GeoIP database type, can't look up Organization/ISP by IP"
  end

  pos = seek_record(ipnum)
  off = pos + (2*@record_length - 1) * @database_segments[0]

  record = atomic_read(MAX_ORG_RECORD_LENGTH, off)
  record = record.sub(/\000.*/n, '')
  record
end

#region(hostname) ⇒ Object

Search the GeoIP database for the specified host, retuning region info.

hostname is a String holding the hosts’s DNS name or numeric IP address.

Returns a Region object with the nine elements:

  • The host or IP address string as requested

  • The IP address string after looking up the host

  • The two-character country code (ISO 3166-1 alpha-2)

  • The three-character country code (ISO 3166-2 alpha-3)

  • The ISO 3166 English-language name of the country

  • The two-character continent code

  • The region name (state or territory)

  • The timezone name, if known



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/geoip.rb', line 254

def region(hostname)
  if (@database_type == GEOIP_CITY_EDITION_REV0 ||
      @database_type == GEOIP_CITY_EDITION_REV1 ||
      @database_type == GEOIP_CITY_EDITION_REV1_V6)
    return city(hostname)
  end

  if (@database_type == GEOIP_REGION_EDITION_REV0 ||
      @database_type == GEOIP_REGION_EDITION_REV1)
    ip = lookup_ip(hostname)
    ipnum = iptonum(ip)
    pos = seek_record(ipnum)
  else
    throw "Invalid GeoIP database type, can't look up Region by IP"
  end

  unless pos == @database_segments[0]
    read_region(pos, hostname, ip)
  end
end