-
Notifications
You must be signed in to change notification settings - Fork 0
/
ipinfo.js
89 lines (70 loc) · 2.38 KB
/
ipinfo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const express = require('express');
const bodyParser = require('body-parser');
const geoip = require('geoip-lite');
const dns = require('dns');
const axios = require('axios');
const app = express();
const port = 3000;
app.use(bodyParser.json());
const ipinfoToken = 'apiinfo.io token';
app.all('/iplookup/:ip', async (req, res) => {
const ipAddress = req.params.ip;
try {
const hostnames = await performReverseDNS(ipAddress);
const geoData = geoip.lookup(ipAddress);
if (!geoData || !geoData.city || !geoData.region || !geoData.country || !geoData.ll) {
const apiData = await getIPInfoFromApi(ipAddress);
const response = {
ip: ipAddress,
hostname: hostnames.length > 0 ? hostnames[0] : null,
city: apiData.city || null,
region: apiData.region || null,
country: apiData.country || null,
loc: apiData.loc || null,
postal: apiData.postal || null,
timezone: apiData.timezone || null,
};
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(response, null, 2));
} else {
const response = {
ip: ipAddress,
hostname: hostnames.length > 0 ? hostnames[0] : null,
city: geoData.city,
region: geoData.region,
country: geoData.country,
loc: `${geoData.ll[0]},${geoData.ll[1]}`,
postal: geoData.zip,
timezone: geoData.timezone,
};
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(response, null, 2));
}
} catch (error) {
res.status(500).json({ error: 'Unable to fetch information for the IP address' });
}
});
function performReverseDNS(ipAddress) {
return new Promise((resolve, reject) => {
dns.reverse(ipAddress, (err, hostnames) => {
if (err) {
reject(err);
} else {
resolve(hostnames || []);
}
});
});
}
async function getIPInfoFromApi(ipAddress) {
try {
const url = `https://ipinfo.io/${ipAddress}?token=${ipinfoToken}`;
const response = await axios.get(url);
return response.data;
} catch (error) {
console.error('Error fetching IP information from ipinfo.io:', error.message);
return {};
}
}
app.listen(port, () => {
console.log(`API server is running on http://localhost:${port}`);
});