Node.js 根据ip获取城市

Node.js

var http = require('http');
var util = require('util');

/**
 * 根据 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('城市: ' + msg.city);
	console.log('msg: ' + util.inspect(msg, true, 8));
})

结果

城市: 北京
msg: { ret: 1,
  desc: '北京蓝汛通信专属电信',
  province: '北京',
  district: '',
  type: '',
  isp: '电信',
  start: '220.181.0.0',
  city: '北京',
  end: '220.181.255.255',
  country: '中国' }

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 "城市:" . $result->city . "<br>";
print_r($result);

?>

结果:

城市:北京
stdClass Object
(
    [ret] => 1
    [start] => 220.181.0.0
    [end] => 220.181.255.255
    [country] => 中国
    [province] => 北京
    [city] => 北京
    [district] => 
    [isp] => 电信
    [type] => 
    [desc] => 北京蓝汛通信专属电信
)

Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s