1. Node.js implementation code
The code copy is as follows:
var http = require('http');
var util = require('util');
/**
* Get the address information based on ip
*/
var getIpInfo = function(ip, cb) {
var sina_server = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=';
var url = sina_server + ip;
http.get(url, function(res) {
var code = res.statusCode;
if (code == 200) {
res.on('data', function(data) {
try {
cb(null, JSON.parse(data));
} catch (err) {
cb(err);
}
});
} else {
cb({ code: code });
}
}).on('error', function(e) { cb(e); });
};
getIpInfo('220.181.111.85', function(err, msg) {
console.log('City: ' + msg.city);
console.log('msg: ' + util.inspect(msg, true, 8));
})
Request result:
Copy the code as follows: City: Xuzhou
{
"ret": 1,
"start": "49.68.0.0",
"end": "49.68.255.255",
"country": "China",
"province": "Jiangsu",
"city": "Xuzhou",
"district": "",
"isp": "电信",
"type": "",
"desc": ""
}
二、PHP实现代码
复制代码代码如下:<?
$ip = "220.181.111.85";
$url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=$ip";
$data = file_get_contents($url);
$result = json_decode($data);
echo "City:" . $result->city . "<br>";
print_r($result);
?>
Request result:
Copy the code as follows: City: Xuzhou
stdClass Object
(
[ret] => 1
[start] => 49.68.0.0
[end] => 49.68.255.255
[country] => China
[province] => Jiangsu
[city] => Xuzhou
[district] =>
[isp] => Telecom
[type] =>
[desc] =>
)