联系客服: iP138客服 |

iP查询接口
  • API接口QQ交流群:177096428   iP138 api接口
  • 数据修正QQ处理群:94181690    iP138数据修正

iP查询接口支持HTTPS(赠送1000次)

简介:获取iP地址对应的省市区以及运营商名称

连接应用数:5642

PHP调用iP查询接口示例:

方法一

                                <?php
                                $ip = '117.25.13.123';
                                $datatype = 'txt';
                                $url = 'http://api.ip138.com/query/?ip='.$ip.'&datatype='.$datatype;

                                $header = array('token:00d5cb1fac5dc5cbfe2ff218292a2dfd33');
                                echo getData($url,$header);   

                                function getData($url,$header){  
                                    $ch = curl_init();  
                                    curl_setopt($ch,CURLOPT_URL,$url);
                                    curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
                                    curl_setopt($ch,CURLOPT_HTTPHEADER,$header); 
                                    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);  
                                    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,3);  
                                    $handles = curl_exec($ch);  
                                    curl_close($ch);  
                                    return $handles;  
                                }
                                ?>
                                

方法二

                                <?php
                                //js引入页面 callback jsonp回调地址
                                $ip = '117.25.13.123';
                                $mid = 35553;
                                $oid = 2;
                                $token = '00d5cb1fac5dc5cbfe2ff218292a2dfd33';
                                $sign = md5("ip=".$ip."&token=".$token);
                                $url = 'http://api.ip138.com/query/';
                                //以下是js引入代码
                                /***
                                /*<script type="text/javascript" src="<?php echo $url.'?ip='.$ip.'&callback=find&oid='.$oid.'&mid='.$mid.'&sign='.$sign;?>"></script>
                                **/
                                ?>
                                

Go语言调用iP查询接口示例:

                                    package main

                                    import (
                                        "encoding/json"
                                        "encoding/xml"
                                        "fmt"
                                        "io/ioutil"
                                        "net/http"
                                    )

                                    const (
                                        URL   = "http://api.ip138.com/query/"
                                        TOKEN = "bd4c2bf9a38ab06f7cae88c9759ee172"
                                    )

                                    //----------------------------------
                                    // iP地址调用示例代码
                                    //----------------------------------

                                    // xml struct
                                    type xmlinfo struct {
                                        Ret  string          `xml:"ret"`
                                        Ip   string          `xml:"ip"`
                                        Data locationxmlInfo `xml:"data"`
                                    }

                                    type locationxmlInfo struct {
                                        Country string `xml:"country"`
                                        Region  string `xml:"region"`
                                        City    string `xml:"city"`
                                        Isp     string `xml:"isp"`
                                        Zip     string `xml:"zip"`
                                        Zone    string `xml:zone`
                                    }

                                    //json struct
                                    type jsoninfo struct {
                                        Ret  string    `json:"ret"`
                                        Ip   string    `json:"ip"`
                                        Data [6]string `json:"data"`
                                    }

                                    func main() {
                                        ipLocation("8.8.8.8","xml")
                                    }

                                    func ipLocation(ip string,dataType string) {

                                        queryUrl := fmt.Sprintf("%s?ip=%s&datatype=%s",URL,ip,dataType)
                                        client := &http.Client{}
                                        reqest, err := http.NewRequest("GET",queryUrl,nil)

                                        if err != nil {
                                            fmt.Println("Fatal error ",err.Error())
                                        }

                                        reqest.Header.Add("token",TOKEN)
                                        response, err := client.Do(reqest)
                                        defer response.Body.Close()

                                        if err != nil {
                                            fmt.Println("Fatal error ",err.Error())
                                        }
                                        if response.StatusCode == 200 {
                                            bodyByte, _ := ioutil.ReadAll(response.Body)

                                            if dataType == "jsonp" {
                                                var info jsoninfo
                                                json.Unmarshal(bodyByte,&info)
                                                fmt.Println(info.Ip)
                                            } else if dataType == "xml" {
                                                var info xmlinfo
                                                xml.Unmarshal(bodyByte,&info)
                                                fmt.Println(info.Ip)
                                            }
                                        }

                                        return
                                    }
                                

Python调用iP查询接口示例:

                                    #!/usr/bin/python
                                    # -*- coding: utf-8 -*-
                                    #python3
                                    import httplib2, urllib
                                    params = urllib.urlencode({'ip':'9.8.8.8','datatype':'jsonp','callback':'find'})
                                    url = 'http://api.ip138.com/query/?'+params
                                    headers = {"token":"8594766483a2d65d76804906dd1a1c6a"}#token为示例
                                    http = httplib2.Http()
                                    response, content = http.request(url,'GET',headers=headers)
                                    print(content)
                                

ASP调用iP查询接口示例:

方法一

                                    <%@LANGUAGE="VBSCRIPT" CODEPAGE="936"%>
                                    <% Option Explicit
                                    '=========================================================
                                    ' File      : .asp
                                    ' Version   : 1.0.0.0
                                    ' Create    : 
                                    ' Modify    : 
                                    '=========================================================
                                    ' 1.0.0.0   : 
                                    '========================================================= %>
                                    <% Dim ip,datatype,token,url

                                    ip = "117.25.13.123"
                                    datatype = "txt"
                                    token = "00d5cb1fac5dc5cbfe2ff218292a2dfd33"    '用户中心查看您的token
                                    url = "http://api.ip138.com/query/?ip="&ip&"&datatype="&datatype&"&token="&token

                                    Response.Write (GetURL(url))

                                    Function GetURL(url)
                                        on error resume next
                                        dim Retrieval
                                        Set Retrieval = Server.CreateObject("MSXML2.ServerXMLHTTP")
                                                Retrieval.setTimeouts 600000, 600000, 600000, 600000
                                                Retrieval.Open "GET", url, false
                                                Retrieval.Send
                                                GetURL = Retrieval.ResponseBody
                                        Set Retrieval = Nothing
                                        GetURL=BytesToBstr(GetURL,"utf-8")
                                    End Function

                                    Function BytesToBstr(strBody,CodeBase)
                                            dim objStream
                                            set objStream = Server.CreateObject("Adodb.Stream")
                                            objStream.Type = 1
                                            objStream.Mode =3
                                            objStream.Open
                                            objStream.Write strBody
                                            objStream.Position = 0
                                            objStream.Type = 2
                                            objStream.Charset = CodeBase
                                            BytesToBstr = objStream.ReadText 
                                            objStream.Close
                                            set objStream = nothing
                                    End Function
                                     %>
                                

方法二

                                    <%@LANGUAGE="VBSCRIPT" CODEPAGE="936"%>
                                    <% Option Explicit
                                    '=========================================================
                                    ' File      : .asp
                                    ' Version   : 1.0.0.0
                                    ' Create    : 
                                    ' Modify    : 
                                    '=========================================================
                                    ' 1.0.0.0   : 
                                    '========================================================= %>
                                    

                                    <% Dim ip,datatype,token,url,strMid,oid,sign
                                    ip = "117.25.13.123"
                                    strMid = 777    '用户中心查看您的mid
                                    oid = 777   '用户中心查看您的oid
                                    datatype = "txt"
                                    token = "00d5cb1fac5dc5cbfe2ff218292a2dfd33"    '用户中心查看您的token
                                    url = "http://api.ip138.com/query/?"
                                    sign = MD5_32("ip="&ip&"&token="&token)
                                    %>

                                    <script type="text/javascript">
                                    
                                    </script>
                                    <script type="text/javascript" src="<%= url&"ip="&ip&"&callback=find&mid="&strMid&"&oid="&oid&"&sign="&sign %>"></script>
                                

Java(android)调用iP查询接口示例:

                                package com.lmqkk.test;

                                import android.os.AsyncTask;
                                import android.os.Build;
                                import android.os.Bundle;
                                import android.support.v7.app.AppCompatActivity;
                                import android.util.Log;

                                import java.io.ByteArrayOutputStream;
                                import java.io.DataOutputStream;
                                import java.io.IOException;
                                import java.io.InputStream;
                                import java.io.UnsupportedEncodingException;
                                import java.net.HttpURLConnection;
                                import java.net.MalformedURLException;
                                import java.net.SocketTimeoutException;
                                import java.net.URL;
                                import java.net.URLEncoder;
                                import java.util.HashMap;
                                import java.util.Map;

                                public class MainActivity extends AppCompatActivity {
                                    @Override
                                    protected void onCreate(Bundle savedInstanceState) {
                                        super.onCreate(savedInstanceState);
                                        setContentView(R.layout.activity_main);

                                        QueryTask task = new QueryTask();
                                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                                            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"8.8.8.8","txt","find","859476648b3de65d76804ff906dd1a1c6a");
                                        } else {
                                            task.execute("8.8.8.8","txt","find","859476648b3de65d76804ff906dd1a1c6a");
                                        }
                                    }

                                    class QueryTask extends AsyncTask<String,Void,String>
                                    {
                                        @Override
                                        protected String doInBackground(String... strings) {
                                            String strUrl = "http://api.ip138.com/query/" ;

                                            Map<String,String> params = new HashMap<String,String>();
                                            params.put("ip",strings[0]);       //可为空
                                            params.put("datatype",strings[1]);
                                            params.put("callback",strings[2]); //可为空
                                            String result = null;

                                            try {
                                                URL url = new URL(strUrl);
                                                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                                                //头信息
                                                HashMap<String, String> header = new HashMap<String,String>();
                                                header.put("token", strings[3]);
                                                for (String headerName : header.keySet()) {
                                                    connection.addRequestProperty(headerName, header.get(headerName));
                                                }

                                                //设置超时时间
                                                connection.setConnectTimeout(5*1000);
                                                //设置允许输入
                                                connection.setDoInput(true);
                                                //设置读取超时:
                                                connection.setReadTimeout(5*1000);
                                                connection.setRequestMethod("GET");
                                                //参数
                                                byte[] body = encodeParameters(params,"UTF-8");
                                                if (body != null)
                                                {
                                                    connection.setDoOutput(true);
                                                    connection.addRequestProperty("Content-Type","application/x-www-form-urlencoded; charset=" + "UTF-8");
                                                    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                                                    out.write(body);
                                                    out.close();
                                                }
                                                int responseCode = connection.getResponseCode();
                                                if (responseCode == -1) {
                                                    throw new IOException("Could not retrieve response code from HttpUrlConnection.");
                                                }
                                                if (responseCode != 200)
                                                {
                                                    return responseCode + "";
                                                }

                                                InputStream inputStream = null;
                                                try {
                                                    inputStream = connection.getInputStream();
                                                } catch (IOException ioe) {
                                                    inputStream = connection.getErrorStream();
                                                }

                                                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                                                byte[] data = new byte[1024];
                                                int len = 0;
                                                if (inputStream != null) {
                                                    try {
                                                        while ((len = inputStream.read(data)) != -1) {
                                                            outputStream.write(data, 0, len);
                                                        }
                                                        result = new String(outputStream.toByteArray(), "UTF-8");
                                                    }
                                                    catch (IOException e) {
                                                        e.printStackTrace();
                                                    }
                                                }

                                                return result;
                                            }catch(SocketTimeoutException e)
                                            {

                                            }catch (MalformedURLException e) {

                                            } catch (IOException e) {

                                            }
                                            return null;
                                        }

                                        @Override
                                        protected void onPostExecute(String s) {
                                            super.onPostExecute(s);
                                            Log.i("Query", "onPostExecute: "+s);
                                        }

                                        byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
                                            if (params == null || params.size() == 0) return null;

                                            StringBuilder encodedParams = new StringBuilder();
                                            try {
                                                for (Map.Entry<String, String> entry : params.entrySet()) {
                                                    encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
                                                    encodedParams.append('=');
                                                    encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
                                                    encodedParams.append('&');
                                                }
                                                return encodedParams.toString().getBytes(paramsEncoding);
                                            } catch (UnsupportedEncodingException uee) {
                                                throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
                                            }
                                        }
                                    }
                                }
                                

Object-C(ios)语言调用iP查询接口示例:

                                //
                                //  ViewController.m
                                //  ApiTest
                                //
                                //  Created by administrator on 16/9/8.
                                //  Copyright © 2016年 star. All rights reserved.
                                //

                                #import "ViewController.h"

                                #define Host @"https://api.ip138.com/query/"

                                @interface ViewController ()<NSXMLParserDelegate>

                                @end

                                @implementation ViewController

                                - (void)viewDidLoad {
                                    [super viewDidLoad];
                                    // Do any additional setup after loading the view, typically from a nib.
                                    NSString * token = @"859476648b3de65d7680494506dd1a1c6a";
                                    
                                    [self executeNetworkWithIP:@"8.8.8.8" dateType:@"xml" callBack:@"" token:token];
                                    
                                }

                                /**
                                 *示例https://api.ip138.com/query/?ip=8.8.8.8&datatype=jsonp&callback=&token=859476648b3de65d7680494506dd1a1c6a
                                 *参数说明:
                                 *1. ip string ip地址 例如 117.25.13.123(可选,默认为请求者iP)
                                 *2. datatype string txt|jsonp|xml(可选,默认为jsonp)
                                 *3. callback string 回调函数 当前参数仅为jsonp格式数据提供(可选,默认为空)
                                 *4. token string 购买服务后会提供(必填)
                                 */

                                - (void)executeNetworkWithIP:(NSString *)ip dateType:(NSString *)dateType callBack:(NSString *)callBack token:(NSString *)token{
                                   
                                    NSString * urlString =[NSString stringWithFormat:@"%@?ip=%@&datatype=%@&callback=%@&token=%@",Host,ip,dateType,callBack,token];
                                    
                                    //准备网络请求
                                    NSString *newStr = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                                    NSURL *url = [NSURL URLWithString:newStr];
                                    NSURLRequest *requst = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
                                    
                                    //请求异步链接
                                    [NSURLConnection sendAsynchronousRequest:requst queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                                        
                                        if (connectionError) {
                                            NSLog(@"jsonError = %@",connectionError);
                                            return ;
                                        }
                                        
                                        //请求格式txt
                                        if ([dateType isEqualToString:@"txt"]) {
                                             NSString *result = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
                                            NSLog(@"result = %@",result);
                                        }
                                        //datatype xml
                                        else if ([dateType isEqualToString:@"xml"]){
                                       
                                            NSString *result = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
                                            NSLog(@"result = %@",result);
                                        }
                                        else{
                                            NSError *jsonError = nil;
                                            NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                            /*如果设置了回调函数,则可截取后再在转化为NSDictionary,也可直接转化为NSString*/
                                            if (callBack&&[callBack length]>0) {
                                                NSRange range = [jsonString rangeOfString:@"("];
                                                range.location++;
                                                range.length = [jsonString length] - range.location - 1;
                                                jsonString = [jsonString substringWithRange:range ];
                                               
                                            }
                                            
                                            NSDictionary *jsonResponse =
                                            [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]
                                                                            options:0
                                                                              error:&jsonError];
                                            if (jsonError) {
                                                NSLog(@"jsonError = %@",jsonError);
                                                return ;
                                            }
                                            NSLog(@"jsonResponse = %@",jsonResponse);
                                        }
                                    }];
                                }

                                - (void)didReceiveMemoryWarning {
                                    [super didReceiveMemoryWarning];
                                    // Dispose of any resources that can be recreated.
                                }

                                @end
                                

C#(.net)调用iP查询接口示例:

方法一

                                using System;
                                using System.Collections.Generic;
                                using System.Web;
                                using System.Net;

                                public class IP138
                                {
                                    public static string GetIPData(string token, string ip = null, string datatype = "txt")
                                    {
                                        if (string.IsNullOrEmpty(ip))
                                        {
                                            ip = HttpContext.Current.Request.UserHostAddress;
                                        }
                                        string url = string.Format("http://api.ip138.com/query/?ip={0}&datatype={1}&token={2}", ip, datatype, token);
                                        using (WebClient client = new WebClient())
                                        {
                                            return client.DownloadString(url);
                                        }
                                    }
                                }

                                string data = IP138.GetIPData("00d5cb1fac5dc5cbfe2ff218222a2dfd33", Request.UserHostAddress);
                                Console.WriteLine(data);
                                Response.Write(data);
                                

方法二

                                <% 
                                string ip =  Request.UserHostAddress;
                                string strMid = "777";    //用户中心查看您的mid
                                string oid = "777";   //用户中心查看您的oid
                                string token = "00d5cb1fac5dc5cbfe2ff218222a2dfd33";    //用户中心查看您的token
                                string url = "http://api.ip138.com/query/?";
                                string str = "ip=" + ip + "&token=" + token;
                                string sign = FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower();
                                %>
                                <script type="text/javascript">
                                function find(str){alert(str.data);}
                                </script>
                                <script type="text/javascript" src="<%= url+"ip="+ip+"&callback=find&mid="+strMid+"&oid="+oid+"&sign="+sign %>"></script>
                                

javascript调用iP查询接口示例:

方法一

                                function ajax(params){
                                    params = params||{};
                                    if (!params.url) {
                                        throw new Error('Necessary parameters are missing.'); //必要参数未填
                                    }
                                    var random = +new Date;
                                    var hander = null;
                                    var options = {
                                        url: '',                                //接口地址
                                        type: 'GET',                            //请求方式
                                        timeout: 5000,                          //超时等待时间
                                        cache: true,                            //缓存 
                                        async: true,                            //是否异步
                                        xhrFields: {},                          //设置XHR对象属性键值对。如果需要,可设置withCredentials为true的跨域请求。
                                        dataType: 'json',                       //请求的数据类型
                                        data: {},                               //参数
                                        jsonp: 'callback',                      //传递请求完成后的函数名
                                        jsonpCallback: 'jsonp_' + random,       //请求完成后的函数名
                                        error: function() {},                   //请求失败后调用
                                        success: function(){},                  //请求成功后调用
                                        complete: function(){}                  //请求完成后调用
                                    };
                                    var formatParams = function(json) {
                                        var arr = [];
                                        for(var i in json) {
                                            arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(json[i]));
                                        }
                                        return arr.join("&");
                                    };
                                    for(var i in params){
                                        switch(i){
                                            case 'type':
                                                options[i] = params[i].toUpperCase();
                                                break;
                                            case 'dataType':
                                                options[i] = params[i].toLowerCase();
                                                break;
                                            default:
                                                options[i] = params[i];
                                        }
                                    }
                                    if(typeof options.data =='object'){
                                        options.data = formatParams(options.data);
                                    }
                                    if(options.dataType=='jsonp'){
                                        options.cache = params.cache||false;
                                        //插入动态脚本及回调函数
                                        var $head = document.getElementsByTagName('head')[0];
                                        var $script = document.createElement('script');
                                        $head.appendChild($script);
                                        window[options.jsonpCallback] = function (json) {
                                            $head.removeChild($script);
                                            window[options.jsonpCallback] = null;
                                            hander && clearTimeout(hander);
                                            options.success(json);
                                            options.complete();
                                        };
                                        //发送请求
                                        if(options.cache){
                                            options.data += options.data?'&_'+random:'_'+random;
                                        }
                                        options.data += '&'+options.jsonp+'='+options.jsonpCallback;
                                        $script.src = (options.url + '?' + options.data).replace('?&','?');
                                        //超时处理
                                        hander = setTimeout(function(){
                                            $head.removeChild($script);
                                            window[options.jsonpCallback] = null;
                                            options.error();
                                            options.complete();
                                        }, options.timeout);
                                    }else{
                                        if(options.cache){
                                            options.data += options.data?'&_'+random:'_'+random;
                                        }
                                        //创建xhr对象
                                        var xhr = new (self.XMLHttpRequest||ActiveXObject)("Microsoft.XMLHTTP");
                                        if(!xhr){
                                            return false;
                                        }
                                        //发送请求
                                        if (options.type == 'POST') {
                                            xhr.open(options.type, options.url, options.async);
                                            xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
                                        }else{
                                            options.url += options.url.indexOf('?')>-1?'&'+options.data:'?'+options.data;
                                            xhr.open(options.type, options.url, options.async);
                                            options.data = null;
                                        }
                                        if(options.xhrFields){
                                            for(var field in options.xhrFields){
                                                xhr[field]= options.xhrFields[field];
                                            }
                                        }
                                        xhr.send(options.data);
                                        //超时处理
                                        var requestDone = false;
                                        hander = setTimeout(function() {
                                            requestDone = true;
                                            if(xhr.readyState != 4){
                                                xhr.abort();
                                                options.error();
                                            }
                                            options.complete();
                                        }, options.timeout);
                                        //状态处理
                                        xhr.onreadystatechange = function(){
                                            if(xhr.readyState == 4&&!requestDone) {
                                                if(xhr.status>=200 && xhr.status<300||xhr.status == 304) {
                                                    var data = options.dataType == "xml" ? xhr.responseXML : xhr.responseText;
                                                    if (options.dataType == "json") {
                                                        try{
                                                            data =  JSON.parse(data);
                                                        }catch(e){
                                                            data = eval('(' + data + ')');
                                                        }
                                                    }
                                                    options.success(data);
                                                } else {
                                                    options.error();
                                                }
                                                hander && clearTimeout(hander);
                                                options.complete();
                                            }
                                        };
                                    }
                                }

                                ajax({
                                    'url':'http://api.ip138.com/query/',
                                    'data':{            //默认自动添加callback参数
                                        'ip':'8.8.8.8', //为空即为当前iP地址
                                        'oid':'35553',
                                        'mid':'2',
                                        'token':'00d5cb1fac5dc5cbfe2ff218292a2dfd33'  //不安全,请定期刷新token,建议进行文件压缩
                                    },
                                    'dataType':'jsonp',
                                    'success':function(json){
                                        console.log(json);
                                    }
                                });
                                

方法二(jQuery)

                                $.ajax({
                                    'url':'http://api.ip138.com/query/',
                                    'data':{            //默认自动添加callback参数
                                        'ip':'8.8.8.8', //为空即为当前iP地址
                                        'oid':'35553',
                                        'mid':'2',
                                        'token':'00d5cb1fac5dc5cbfe2ff218292a2dfd33'  //不安全,请定期刷新token,建议进行文件压缩
                                    },
                                    'dataType':'jsonp',
                                    'success':function(json){
                                        console.log(json);
                                    }
                                });