Class: Ipwhois::Client

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

Overview

Ruby client for the ipwhois.io IP Geolocation API.

Quick start


# Free plan (no API key, ~1 request/second per client IP)
client = Ipwhois::Client.new
info   = client.lookup('8.8.8.8')

# Paid plan (with API key, higher limits, bulk, security data, …)
client = Ipwhois::Client.new('YOUR_API_KEY')
info   = client.lookup('8.8.8.8', lang: 'en', security: true)

# Bulk lookup — up to 100 IPs in one call (paid only)
list = client.bulk_lookup(['8.8.8.8', '1.1.1.1', '208.67.222.222'])

# HTTPS is enabled by default. Pass `ssl: false` to fall back to HTTP.

Error handling


The library never raises. All errors — invalid input, network failure, API-level errors (bad IP, bad key, rate limit, …) — are returned in the response hash with ‘’success’ => false` and a ‘’message’‘. Just check `info` after every call.

Constant Summary collapse

HOST_FREE =

Free-plan endpoint host (used when no API key is provided).

'ipwho.is'
HOST_PAID =

Paid-plan endpoint host (used when an API key is provided).

'ipwhois.pro'
BULK_LIMIT =

Maximum number of IP addresses allowed in a single bulk request.

100
SUPPORTED_LANGUAGES =

Languages supported by the ‘lang` option.

%w[en ru de es pt-BR fr zh-CN ja].freeze
DEFAULT_TIMEOUT =
10
DEFAULT_CONNECT_TIMEOUT =
5
MAX_REDIRECTS =
3

Instance Method Summary collapse

Constructor Details

#initialize(api_key = nil, **options) ⇒ Client

Returns a new instance of Client.

Parameters:

  • api_key (String, nil) (defaults to: nil)

    Your ipwhois.io API key. Omit (or pass nil) for the free plan.

  • options (Hash)

    Optional defaults applied to every request. Recognised keys: ‘:lang`, `:fields`, `:security`, `:rate`, `:ssl`, `:timeout`, `:connect_timeout`, `:user_agent`.



54
55
56
57
58
59
60
61
# File 'lib/ipwhois/client.rb', line 54

def initialize(api_key = nil, **options)
  @api_key         = api_key
  @timeout         = options.delete(:timeout)         || DEFAULT_TIMEOUT
  @connect_timeout = options.delete(:connect_timeout) || DEFAULT_CONNECT_TIMEOUT
  @user_agent      = options.delete(:user_agent)      || "ipwhois-ruby/#{Ipwhois::VERSION}"
  @ssl             = options.key?(:ssl) ? options.delete(:ssl) != false : true
  @defaults        = options
end

Instance Method Details

#bulk_lookup(ips, **options) ⇒ Array<Hash>, Hash

Look up information for multiple IP addresses in a single request.

Uses the GET / comma-separated form documented at ipwhois.io/documentation/bulk — up to 100 addresses per call. Each address counts as one credit.

Available on the Business and Unlimited plans only.

Per-IP errors are returned inline with ‘’success’ => false` for the affected entry; the rest of the batch is still usable. If the whole call fails, the response is a single error hash with ‘’success’ => false` instead of an array.

Parameters:

  • ips (Array<String>)

    Up to 100 IPv4/IPv6 addresses (mixable).

  • options (Hash)

    Per-call options (same keys as #lookup).

Returns:

  • (Array<Hash>, Hash)

    Array of per-IP results on success; a single error hash on whole-batch failure. The library never raises.



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/ipwhois/client.rb', line 103

def bulk_lookup(ips, **options)
  unless ips.is_a?(Array)
    return {
      'success'    => false,
      'message'    => 'Bulk lookup requires an Array of IP addresses.',
      'error_type' => 'invalid_argument'
    }
  end

  if ips.empty?
    return {
      'success'    => false,
      'message'    => 'Bulk lookup requires at least one IP address.',
      'error_type' => 'invalid_argument'
    }
  end

  if ips.size > BULK_LIMIT
    return {
      'success'    => false,
      'message'    => "Bulk lookup accepts at most #{BULK_LIMIT} IP addresses per call, got #{ips.size}.",
      'error_type' => 'invalid_argument'
    }
  end

  error = validate_options(options)
  return error if error

  # The API accepts addresses joined by commas — no URL-encoding of the
  # commas themselves, otherwise the path is misinterpreted.
  joined = ips.map { |ip| escape_path_segment(ip.to_s) }.join(',')
  url    = build_url("/bulk/#{joined}", options)

  request(url)
end

#lookup(ip = nil, **options) ⇒ Hash

Look up information for a single IP address.

Pass ‘nil` (or call without arguments) to look up the caller’s own public IP, as documented at ipwhois.io/documentation.

The library never raises — check ‘result` after every call.

Parameters:

  • ip (String, nil) (defaults to: nil)

    IPv4 or IPv6 address. nil = current IP.

  • options (Hash)

    Per-call options: ‘:lang`, `:fields`, `:security`, `:rate`.

Returns:

  • (Hash)

    Decoded JSON response. On any error (API, network, bad input) the hash contains ‘’success’ => false` and ‘’message’‘. The library never raises.



76
77
78
79
80
81
82
83
84
# File 'lib/ipwhois/client.rb', line 76

def lookup(ip = nil, **options)
  error = validate_options(options)
  return error if error

  path = ip.nil? ? '/' : "/#{escape_path_segment(ip.to_s)}"
  url  = build_url(path, options)

  request(url)
end

#set_connect_timeout(seconds) ⇒ self

Set the connection timeout in seconds (default: 5).

Returns:

  • (self)


184
185
186
187
# File 'lib/ipwhois/client.rb', line 184

def set_connect_timeout(seconds)
  @connect_timeout = seconds
  self
end

#set_fields(fields) ⇒ self

Restrict every response to a fixed set of fields by default.

Include ‘’success’‘ in the list if you rely on `info` for error checking — when `:fields` is set, the API only returns the fields you ask for.

Parameters:

  • fields (Array<String>)

    For example: %w[success country city flag.emoji].

Returns:

  • (self)


156
157
158
159
# File 'lib/ipwhois/client.rb', line 156

def set_fields(fields)
  @defaults[:fields] = fields
  self
end

#set_language(lang) ⇒ self

Set the default language used when none is supplied per call.

Parameters:

Returns:

  • (self)


143
144
145
146
# File 'lib/ipwhois/client.rb', line 143

def set_language(lang)
  @defaults[:lang] = lang
  self
end

#set_rate(enabled) ⇒ self

Enable or disable the ‘rate` block in responses by default.

Returns:

  • (self)


170
171
172
173
# File 'lib/ipwhois/client.rb', line 170

def set_rate(enabled)
  @defaults[:rate] = enabled
  self
end

#set_security(enabled) ⇒ self

Enable or disable threat-detection data on every call by default.

Returns:

  • (self)


163
164
165
166
# File 'lib/ipwhois/client.rb', line 163

def set_security(enabled)
  @defaults[:security] = enabled
  self
end

#set_timeout(seconds) ⇒ self

Set the per-request total timeout in seconds (default: 10).

Returns:

  • (self)


177
178
179
180
# File 'lib/ipwhois/client.rb', line 177

def set_timeout(seconds)
  @timeout = seconds
  self
end

#set_user_agent(user_agent) ⇒ self

Override the User-Agent header sent with every request.

Returns:

  • (self)


191
192
193
194
# File 'lib/ipwhois/client.rb', line 191

def set_user_agent(user_agent)
  @user_agent = user_agent
  self
end