DELPHI 代码查询一个 IP 地址的归属地


本文整理自网络,侵删。

 
网上搜了一下资料,发现公开的查询 API 有几个:

1. 新浪的。访问了,没有结果返回;

2. 腾讯的。访问了,返回结果是这个页面已经找不到。

3. 淘宝的,能用。

淘宝的 API 接口:http://ip.taobao.com/service/getIpInfo.php?ip=

这是一个 http 的调用,返回值是 JSON 格式。可以直接用浏览器去访问这个 URL 然后看到返回值。

例子:

http://ip.taobao.com/service/getIpInfo.php?ip=103.45.2.23


返回值是:

{"code":0,"data":{"ip":"103.45.2.23","country":"中国","area":"","region":"广东","city":"东莞","county":"XX","isp":"电信","country_id":"CN","area_id":"","region_id":"440000","city_id":"441900","county_id":"xx","isp_id":"100017"}}


上述 JSON 的格式,用 DELPHI 的代码是可以解析的。

从一个 HTTP 的 URL 获取返回值,最简单的办法是用 Indy 的 TIdHTTP 控件。

例子代码如下:
procedure TFmMain.BtnIPQueryClick(Sender: TObject);
var
  S: string;
  JSONStr: string;
  country, area, region, city: string;
begin
  //EditIP 是输入的要查询的 IP 地址
  S := 'http://ip.taobao.com/service/getIpInfo.php?ip=';

  JSONStr := IdHTTP1.Get(S + EditIP.Text);
  if JSONStr = '' then Exit;

  ParseIPAddressFromTaoBaoJSON(JSONStr, country, area, region, city);
  Memo1.Lines.Add(country + '; ' + area + '; ' + region + '; ' + City);
end;

上述代码中使用了一个专门针对淘宝返回的 JSON 的字符串解析的函数
ParseIPAddressFromTaoBaoJSON

这个函数使用了 TJSONValue 需要 uses System.JSON;

代码如下:
function TFmMain.ParseIPAddressFromTaoBaoJSON(const JSONStr: string; var country,
  area, region, city: string): Boolean;
var
  Obj: TJSONValue;
  AValue: TJSONValue;
begin
  Obj := TJSONObject.ParseJSONValue(JSONStr);

  if Obj is TJSONObject then
  begin
    AValue := TJSONObject(Obj).Values['data'];
  end;


  if AValue is TJSONObject then
  begin
    country := TJSONObject(AValue).Values['country'].ToString;
    area := TJSONObject(AValue).Values['area'].ToString;
    region := TJSONObject(AValue).Values['region'].ToString;
    city := TJSONObject(AValue).Values['city'].ToString;
  end;
end;
这段代码,目前测试通过。日期:2018-6-24.   未来是否能用,得看淘宝的这个服务是否还在。 

相关阅读 >>

Delphi10 一段汇编程序

Delphi twebbrowser 用法

winapi 字符及字符串函数(8): ischarupper - 是否是个大写字母

Delphi 时钟

Delphi fmx app 设置 程序图标,闪屏,程序名

Delphi getprocessisadmin()判断exe是否以管理员身份启动

Delphi 实现检测线程类tthread是否结束

Delphi 检测链接和获取链接内容

Delphi编写提取exe文件的ico图标

Delphi changefileext 更改文件的后缀扩展名

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...