Skip to content

Commit ff3ba3f

Browse files
committed
Look up addresses, AS numbers and domains
The VPNDetection client's lookup surface, ported: isBogon on the client and as Bogon.isBogon, lookup, lookupBatch, myIp and myEntitlement with their async forms and LookupOptions or BatchOptions, the bogon answer, IPv4-mapped addresses read as the address they carry, the per-client cache with shared misses, the batch in chunks of 1000, and a lookup refusal's message read from its error member. lookupAsn and lookupDomain take lookup's shape and are neither cached nor batched. InternetData's own: Result, AsnResult and DomainResult hand back a member every plan answers as it is and the rest as an Optional, empty when the plan leaves it out; a list or map left out reads as absent, not empty. lookup refuses a string that is not an address before sending, since the API answers an AS or a domain at that path. The client is AutoCloseable, as the batch and async pool make it, and Caffeine is back for the cache. The emitted corpus and bogon table come with the code that passes on them.
1 parent 6c350dc commit ff3ba3f

26 files changed

Lines changed: 9953 additions & 259 deletions

‎README.md‎

Lines changed: 185 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
The official Java client library for the [InternetData](https://internetdata.io) API.
77

8-
The library lists the IP databases your organization is licensed for, tells you what is inside each one, and downloads them.
8+
It looks up what every InternetData database says about an IP address, an AS or a domain, and lists, describes and downloads the databases your organization is licensed for.
99

1010
## Getting Started
1111

@@ -25,19 +25,185 @@ Requires Java 17 or newer. HTTP is the JDK's own `java.net.http.HttpClient`, so
2525

2626
## Usage
2727

28-
Every database endpoint is licensed, so you need an API key carrying the `db.download` scope. Create one in the console, then:
28+
**No API key needed to start.** Unlimited, the free plan, answers the Tor, relay, anycast, carrier, satellite and service flags, `location` to the country, `asn`, `company`, `hostname` and the abuse email, with no daily or monthly cap, with a key or without one.
2929

3030
```java
3131
import io.internetdata.InternetData;
32+
import io.internetdata.Result;
3233

34+
InternetData client = InternetData.create();
35+
36+
Result result = client.lookup("146.70.116.130");
37+
System.out.println(result.isTor()); // false
38+
System.out.println(result.location().getCountry()); // the ISO 3166 country code
39+
System.out.println(result.asn().getName()); // who runs the announcing network
40+
```
41+
42+
Build the client once and keep it. It owns a connection pool, a cache and a thread pool, and it is thread safe.
43+
44+
### With an API key
45+
46+
Every paid plan answers every field: `is_vpn`, the four proxy flags, `is_hosting` and `is_cdn`, the detail behind each flag, the city and coordinates, whois and more. The plans differ only in how many lookups they include, and a free account tries every field, 100 lookups a day. Create a key in the [console](https://app.internetdata.io), then pass it in:
47+
48+
```java
3349
InternetData client = InternetData.create(System.getenv("INTERNETDATA_API_KEY"));
50+
51+
Result result = client.lookup("146.70.116.130");
52+
System.out.println(result.isVpn()); // Optional[true], on a paid plan
53+
System.out.println(result.vpn().get().getProvider()); // the VPN service, on a paid plan
54+
System.out.println(result.location().getCity()); // null on Unlimited
55+
```
56+
57+
### AS numbers and domains
58+
59+
```java
60+
AsnResult asn = client.lookupAsn(9009);
61+
System.out.println(asn.name()); // M247 Europe SRL
62+
System.out.println(asn.prefixes()); // what it announces, on a paid plan
63+
64+
DomainResult domain = client.lookupDomain("example.com");
65+
System.out.println(domain.isRegistered()); // true
66+
System.out.println(domain.dns()); // its records, on a paid plan
67+
```
68+
69+
Neither is cached, and both have `CompletableFuture` variants: `lookupAsnAsync` and `lookupDomainAsync`.
70+
71+
### Your own address
72+
73+
```java
74+
Result result = client.myIp();
75+
System.out.println(result.ip()); // the address we saw this call come from
76+
```
77+
78+
Same answer `lookup` would give for that address, and the same cost against your allowance. It is deliberately not cached: which address you are is the whole question, and a machine that moves between networks would otherwise be told where it used to be.
79+
80+
### Your plan and usage
81+
82+
```java
83+
Entitlement acct = client.myEntitlement();
84+
System.out.println(acct.getPlan().getKey()); // the plan your key is on
85+
System.out.println(acct.getUsage().getRequests()); // 580
86+
System.out.println(acct.getUsage().getWindowEnd()); // when the allowance resets
87+
```
88+
89+
Usage counts against the anniversary of your subscription on a paid plan, not the calendar month and not the billing period, and against the UTC day on the free plan; it is the same number a lookup is gated on. `getHardLimit()` is `null` on an uncapped plan, which is not the same as zero.
90+
91+
`myIpAsync()` and `myEntitlementAsync()` return a `CompletableFuture` of the same thing.
92+
93+
### Batch lookup
94+
95+
Look up as many addresses as you like in one call. Bogons and cached answers are handled locally, and everything else goes to the batch endpoint in chunks of up to 1000 addresses, in parallel. The batch endpoint needs a paid plan:
96+
97+
```java
98+
var results = client.lookupBatch(List.of("146.70.116.130", "8.8.8.8", "1.1.1.1"));
99+
100+
for (var entry : results.entrySet()) {
101+
if (!entry.getValue().isSuccess()) {
102+
System.err.println(entry.getKey() + ": " + entry.getValue().error().get().getMessage());
103+
continue;
104+
}
105+
System.out.println(entry.getKey() + ": " + entry.getValue().orElseThrow().isVpn());
106+
}
107+
```
108+
109+
Results are keyed by address, in the order you first listed each one, so duplicates in your list collapse into a single entry and one address failing never loses the rest: it carries its error as its value, with the status the API would have given that address on its own.
110+
111+
How many chunks are in flight at once, how many times a failed chunk is retried, and how long each attempt may take are configurable per call:
112+
113+
```java
114+
var results = client.lookupBatch(manyIps,
115+
new BatchOptions().concurrency(4).retries(4).requestTimeout(Duration.ofSeconds(10)));
116+
```
117+
118+
There are `CompletableFuture` variants of both, for when you would rather not block:
119+
120+
```java
121+
client.lookupAsync("146.70.116.130").thenAccept(r -> System.out.println(r.isTor()));
122+
client.lookupBatchAsync(manyIps).thenAccept(results -> System.out.println(results.size()));
123+
```
124+
125+
### Caching
126+
127+
Address lookups are cached by default, so repeat lookups of the same address are free:
128+
129+
```java
130+
InternetData client = InternetData.create();
131+
132+
Result result = client.lookup("146.70.116.130"); // API request
133+
Result result2 = client.lookup("146.70.116.130"); // no API request, the answer was cached
134+
```
135+
136+
You can change the default cache variables (max size, TTL, etc) on initialization, or even disable it:
137+
138+
```java
139+
InternetData client = InternetData.builder()
140+
.cacheSize(50_000)
141+
.cacheTtl(Duration.ofHours(6))
142+
.build();
143+
144+
InternetData clientNoCache = InternetData.builder().cacheEnabled(false).build();
34145
```
35146

36-
Build the client once and keep it. It owns a connection pool, and it is thread safe.
147+
### Private and reserved addresses
37148

38-
The database calls hang off `client.database()`, which is where the sibling VPNDetection library keeps the same seven.
149+
Private, loopback, link-local, documentation and multicast addresses (and their IPv6 equivalents, including the 6to4 and Teredo ranges) are answered by the library itself, so they cost no request and no quota:
150+
151+
```java
152+
Result result = client.lookup("192.168.1.1");
153+
result.isBogon(); // true
154+
result.isTor(); // false
155+
```
39156

40-
### What you can see
157+
The check is available on the client, which is handy when your inputs are addresses anyway:
158+
159+
```java
160+
client.isBogon("10.0.0.1"); // true
161+
client.isBogon("8.8.8.8"); // false
162+
```
163+
164+
It is also available on its own, if you want it without a client:
165+
166+
```java
167+
import static io.internetdata.Bogon.isBogon;
168+
169+
isBogon("10.0.0.1"); // true
170+
```
171+
172+
### Errors
173+
174+
Failures throw an `InternetDataException` carrying a `kind()` and a `retryable()` flag. It is unchecked, so it travels through a stream or a future without being wrapped first:
175+
176+
```java
177+
import io.internetdata.InternetDataException;
178+
179+
try {
180+
client.database().download("bogon_ip_v1", DatabaseFormat.MMDB, Path.of("bogon_ip_v1.mmdb"));
181+
} catch (InternetDataException e) {
182+
System.err.println(e.kind() + " " + e.getMessage() + " retryable=" + e.retryable());
183+
}
184+
```
185+
186+
`kind()` is one of `BAD_REQUEST`, `UNAUTHORIZED`, `FORBIDDEN`, `RATE_LIMITED`, `QUOTA_EXCEEDED`, `SERVER_ERROR` or `NETWORK`. `getMessage()` is the API's own word where it sent one, so a database refusal reads `NOT_LICENSED` or `LICENSE_EXPIRED` rather than "403".
187+
188+
Note that `RATE_LIMITED` and `QUOTA_EXCEEDED` both arrive as HTTP 429 and are not the same thing. A rate limit carries `Retry-After`, so retrying later works, and the library retries it for you, as it does 5xx and transport failures; a spent quota needs your allowance raised or the window to roll over, and the library never retries it, nor any other client error.
189+
190+
### Timeouts
191+
192+
Each attempt at an API call may take 30 seconds, response body included, before it fails as a retryable `NETWORK` error. Change it for the client, or for a single call:
193+
194+
```java
195+
InternetData client = InternetData.builder().requestTimeout(Duration.ofSeconds(5)).build();
196+
197+
Result result = client.lookup("146.70.116.130", new LookupOptions().requestTimeout(Duration.ofSeconds(2)));
198+
```
199+
200+
The bound is per attempt, so a call that is retried can take longer in total. Database downloads are not bounded by it, since a large one can take minutes.
201+
202+
### Databases
203+
204+
If your key carries the `db.download` scope, the databases your organization is licensed for are available through `client.database()`, which is where the sibling VPNDetection library keeps the same seven calls.
205+
206+
#### What you can see
41207

42208
```java
43209
import io.internetdata.model.Database;
@@ -52,7 +218,7 @@ A license covers a database *family* (`bogon_ip`), while a download names a *ver
52218

53219
`getStanding()` is `LICENSED` for a live grant, `EXPIRED` for one whose term has ended, and `UNLICENSED` for a database published but never bought, which is how you discover what else exists.
54220

55-
### What is inside one
221+
#### What is inside one
56222

57223
```java
58224
import io.internetdata.model.DatabaseMetadata;
@@ -67,7 +233,7 @@ meta.getSample(); // a few real rows, per format
67233

68234
Poll this to decide whether today's build is worth fetching, and to budget a transfer before you start one.
69235

70-
### Downloading
236+
#### Downloading
71237

72238
```java
73239
import io.internetdata.DatabaseFormat;
@@ -103,7 +269,7 @@ client.database().download("vpn_ip_v1", DatabaseFormat.MMDB, Path.of("vpn_ip_v1.
103269

104270
A build is kept 7 days. Past that the call throws `BAD_REQUEST` with the message `BUILD_GONE`, and downloading without a build fetches the live one.
105271

106-
### Verifying a download
272+
#### Verifying a download
107273

108274
```java
109275
import io.internetdata.model.DatabaseChecksums;
@@ -112,7 +278,7 @@ DatabaseChecksums sums = client.database().checksums("bogon_ip_v1", DatabaseForm
112278
sums.getSha256();
113279
```
114280

115-
### Download history
281+
#### Download history
116282

117283
Your organization's recent attempts, newest first, refusals included, which is what answers "it stopped working":
118284

@@ -123,24 +289,6 @@ client.database().downloads().forEach(d ->
123289
client.database().downloads(10); // newest ten
124290
```
125291

126-
### Errors
127-
128-
Failures throw an `InternetDataException` carrying a `kind()` and a `retryable()` flag. It is unchecked, so it travels through a stream or a future without being wrapped first:
129-
130-
```java
131-
import io.internetdata.InternetDataException;
132-
133-
try {
134-
client.database().download("bogon_ip_v1", DatabaseFormat.MMDB, Path.of("bogon_ip_v1.mmdb"));
135-
} catch (InternetDataException e) {
136-
System.err.println(e.kind() + " " + e.getMessage() + " retryable=" + e.retryable());
137-
}
138-
```
139-
140-
`kind()` is one of `BAD_REQUEST`, `UNAUTHORIZED`, `FORBIDDEN`, `RATE_LIMITED`, `QUOTA_EXCEEDED`, `SERVER_ERROR` or `NETWORK`. `getMessage()` is the API's own result code where it sent one, so a refusal reads `NOT_LICENSED` or `LICENSE_EXPIRED` rather than "403".
141-
142-
`RATE_LIMITED` is a 429 that carries `Retry-After`, and the library retries it for you, as it does 5xx and transport failures. `QUOTA_EXCEEDED` is a 429 without one, which it never retries, and it retries no other client error either. InternetData's database API has no quota, so you won't see `QUOTA_EXCEEDED` from it.
143-
144292
### Sign in with OAuth (device flow)
145293

146294
A program running on the person's own machine can let them sign in with a browser and pick one of their API keys, instead of asking them to paste it:
@@ -190,6 +338,16 @@ ClientRegistration registration = client.oauth().register(List.of("http://127.0.
190338

191339
Each redirect URI must be https on a public host name, or http on a loopback address, which then matches any port. Nothing is kept until a person approves the client, so an app with no client ID saved can simply register again.
192340

341+
### Absent is not false
342+
343+
Unlimited leaves out `isVpn()`, the four proxy flags, `isHosting()` and `isCdn()`, the detail behind every flag but Tor's and relay's, whois and `hostedDomains()`, and inside `location()` the city, region and coordinates; a free-plan key's answer carries `trialExpired()`, true once its daily trial is spent. Every member a plan may leave out is an `Optional`, where empty means "not in your plan" rather than "checked, and no", and one inside `location()`, `asn()`, `company()` or `abuse()` is null.
344+
345+
```java
346+
result.isVpn().orElse(false); // when you only want the flag
347+
result.isVpn().isEmpty(); // on Unlimited: not in your plan
348+
result.trialExpired().orElse(false); // a free-plan key's daily trial is spent
349+
```
350+
193351
## Other Libraries
194352

195353
There are official InternetData client libraries available for many languages including PHP, Python, Go, Java, and Ruby. See our GitHub at https://github.com/internetdata for more.

0 commit comments

Comments
 (0)