This article describes how to obtain the geographic location of Node. js and PHP Based on the ip address. You can use the Sina interface to obtain the City Based on the ip address. For more information, see Node. js implementation code.
The Code is as follows:
Var http = require ('http ');
Var util = require ('til ');
/**
* Obtain the address information based on the ip address
*/
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 ('1970. 181.111.85 ', function (err, msg ){
Console. log ('city: '+ msg. city );
Console. log ('msg: '+ util. inspect (msg, true, 8 ));
})
Request result:
The Code is as follows:
City: Xuzhou
{
"Ret": 1,
"Start": "49.68.0.0 ",
"End": "49.68.0000255 ",
"Country": "China ",
"Province": "Jiangsu ",
"City": "Xuzhou ",
"District ":"",
"Isp": "Telecom ",
"Type ":"",
"Desc ":""
}
Ii. PHP implementation code
The Code is as follows:
$ 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 ."
";
Print_r ($ result );
?>
Request result:
The Code is as follows:
City: Xuzhou
StdClass Object
(
[Ret] => 1
[Start] => 49.68.0.0
[End] => 49.68.0000255
[Country] => China
[Province] => Jiangsu
[City] => Xuzhou
[District] =>
[Isp] => China Telecom
[Type] =>
[Desc] =>
)