Call the aggregated data API to obtain the IP address

1. Introduction of the author

Shuaixiu Wang, male, graduate student of 2022, School of Electronic Information, Xi'an Polytechnic University
Research direction: Machine Vision and Artificial Intelligence
Email: [email protected]

Zhang Siyi, female, School of Electronic Information, Xi'an Polytechnic University, 2022 graduate student, Zhang Hongwei Artificial Intelligence Research Group
Research direction: machine vision and artificial intelligence
Email: [email protected]

2. Introduction

2.1 Introduction to Aggregate Data API

Aggregate Data API is a platform that provides various data API interfaces, including various types of data interfaces such as weather forecast, stock, and IP address query.
The characteristics of the aggregated data API platform include convenience and ease of use, high efficiency and stability, customization, providing a variety of development tools and strong technical support, etc., which can help developers quickly and easily obtain the required data.

2.2 Purpose and significance of querying IP address

The purpose of calling the aggregation API to query IP addresses is to obtain information related to specific IP addresses. For example, query the location information of the IP address, ISP service provider, operator, IP segment, geographical location and other information.
Application scenarios:
1. Anti-fraud and risk control: By querying the IP address, it can be judged whether the IP address is risky, such as whether it is a malicious IP address or a proxy server.
2. Website traffic analysis: Through IP address query, you can know the source of the website, visits, user behavior and other data information, which is helpful for website traffic analysis and business optimization.
3. Through IP address query, network activities and attack behaviors can be monitored and early warning, so as to ensure network security.

3. Call the aggregation data API to query the IP address

3.1 Call aggregated data API

The aggregated data official website provides the function of IP address query, and the specific calling process is as follows:
1. First register and log in on the aggregated data official website, and perform real-name authentication.
2. Then search for the IP address query, activate the IP address query service, and generate a request Key for calling the aggregation data API.
3. Finally, copy the example code provided by the official website, and fill in the Key you applied for in the corresponding position of the code.

3.2 Code implementation

import urllib.request, urllib.error, urllib.parse, sys, json
import importlib
importlib.reload(sys)
url = 'http://apis.juhe.cn/ip/ipNew'
params = {
    "ip": "x.xx.xx.xxx",  # 查询的IP地址
    "key": "申请的KEY",  # 您申请的接口API接口请求Key
}
querys = urllib.parse.urlencode(params).encode("utf-8") 
#使用 urlencode 函数将参数编码为 URL 格式,再进行 UTF-8 编码。
request = urllib.request.Request(url, data=querys) #构建一个 request 对象,包括请求的地址和请求的参数
response = urllib.request.urlopen(request) #使用 urlopen() 函数向 API 发送请求,获取响应
content = response.read() #读取响应内容
if (content):
    try:
        result = json.loads(content) #判断返回的内容是否存在
        error_code = result['error_code']  #从响应内容字典中获取 error_code 的值,判断请求是否成功。
        if (error_code == 0):
            country = result['result']['Country']  
            province = result['result']['Province']
            city = result['result']['City']
            isp = result['result']['Isp']  #获取IP归属地的国家、省份、城市、运营商信息。
            print("国家:%s\n省份:%s\n城市:%s\n运营商:%s" % (country, province, city, isp))
        else:
            print("请求失败:%s %s" % (result['error_code'], result['reason']))
    except Exception as e:
        print("解析结果异常:%s" % e)
else:
    # 可能网络异常等问题,无法获取返回内容,请求异常
    print("请求异常")

3.3 Experimental results

Country: China
Province: Shaanxi Province
City: Xi'an
Carrier: China Telecom

3.4 Precautions

Version problem : urllib2 is one of the standard modules in Python2.x, but it is split into two modules, urllib.request and urllib.error, in Python3.x. So, if you try to use urllib2 in Python3, you will get a ModuleNotFoundError error.
Solution : Make changes to the function according to the python technical documentation or use python2to3.py to convert.
Calling other types of APIs: ip-api.com is a website provided by developers in Germany. Although it is created and maintained by German developers, it provides a global IP address query service, which can query the IP address country, region, city, zip code, latitude and longitude information of any country or region. No matter which country you are in, you can use ip-api.com to query the information of IP address. And do not need to register an account, unlimited calls for free. Therefore, this API can also be called for IP address query.
Relevant code :

import requests
def ip_address_lookup(ip_address):
    url = f"http://ip-api.com/json/{ip_address}"
    response = requests.get(url)
    data = response.json()
    if data['status'] == 'success':
        print(f"IP地址:{data['query']}")
        print(f"国家:{data['country']}")
        print(f"地区:{data['regionName']}")
        print(f"城市:{data['city']}")
        print(f"邮政编码:{data['zip']}")
        print(f"经度:{data['lon']}")
        print(f"纬度:{data['lat']}")
    else:
        print("IP地址查询失败")
ip_address_lookup("需要查询的IP地址")

Guess you like

Origin blog.csdn.net/m0_37758063/article/details/131384881