当前位置:首页 > Python > 正文内容

CDN检测器:Python编程实现域名CDN使用情况的检测

chanra1n4个月前 (04-09)Python981

在介绍这个用Python编写的CDN检测器工具之前,我们首先需要理解什么是CDN。CDN,全称内容分发网络(Content Distribution Network),是一种网络技术,它可以使用户更快地获取到所需内容。CDN通过将内容分布到全球各地的服务器上,用户在访问时可以直接从其网络位于最近的服务器上获得内容,大大提高了访问的速度和稳定性。

今天,我想向大家介绍的是一个由myfpga.cn的工程师ChanRa1n编写的用于检测域名是否使用了CDN的Python工具。这个工具使用一些Python的重要模块,如socket、ipaddress、requests等。

代码如下:

# -*- coding: utf-8 -*-
"""
Detect if a domain name is using CDN.

This module checks if the given URL is using a CDN by resolving the domain name's IP and comparing it with known CDN IP ranges.
It also includes a secondary check using the socket.getaddrinfo method.

Author: ChanRa1n
Email: chenyu@myfpga.cn
Creation Date: 2024/04/09
License: This software is intended for educational and learning purposes only. No warranty for software availability and security. Protect copyright and mitigate risks.

This software is provided "as is" without any guarantees or warranty. In association with the product, myfpga.cn makes no warranties of any kind, either express or implied, including but not limited to warranties of merchantability, fitness for a particular purpose, of title, or of noninfringement of third party rights. Use of the software by a user is at the user's risk.

Only for learning and educational purposes.
"""

import socket
import ipaddress
import os
import requests

def is_ip_in_cdn(ip, cdn_ranges):
    ip_obj = ipaddress.ip_address(ip)
    for cdn_range in cdn_ranges:
        if ip_obj in ipaddress.ip_network(cdn_range, strict=False):
            return True
    return False

def read_cdn_ranges(filename='cdn_list.txt'):
    # Check if the file exists in the current directory
    if not os.path.exists(filename):
        # If the file does not exist, try to fetch it from the web
        try:
            response = requests.get('https://myfpga.cn/library/Internet/cdn_list.txt')
            response.raise_for_status()  # Raises an HTTPError if the HTTP request returned an unsuccessful status code
            # Split the content into lines
            cdn_list_raw = response.text.splitlines()
        except requests.HTTPError as err:
            print(f"Failed to retrieve cdn_list.txt from the web: {err}")
            return []  # Return an empty list on error
    else:
        with open(filename, 'r') as file:
            cdn_list_raw = file.readlines()
    # Filter comments and empty lines
    return [line.strip() for line in cdn_list_raw if line.strip() and not line.startswith('#')]

def check_cdn_by_getaddrinfo(hostname):
    try:
        addr_info = socket.getaddrinfo(hostname, None)
        return len(set([info[4][0] for info in addr_info])) > 1
    except socket.error:
        return False

def check_cdn(url, cdn_list_file='cdn_list.txt'):
    hostname = url.split("//")[-1].split("/")[0]
   
    cdn_ranges = read_cdn_ranges(cdn_list_file)
    if not cdn_ranges:  # If cdn_ranges is empty, either file read or web fetch failed
        return False
   
    try:
        ip = socket.gethostbyname(hostname)
        if is_ip_in_cdn(ip, cdn_ranges):
            return True
        else:
            return check_cdn_by_getaddrinfo(hostname)
    except socket.gaierror:
        return False

def is_using_cdn(url):
    return check_cdn(url)

# 测试代码
if __name__ == "__main__":
    url_to_test = input("请输入URL:")
    if is_using_cdn(url_to_test):
        print("检测结果:是CDN或检测失败。")
    else:
        print("检测结果:不是CDN。")

运行效果如图:

image.png

扫描二维码推送至手机访问。

版权声明:本文由我的FPGA发布,如需转载请注明出处。

本文链接:http://myfpga.cn/index.php/post/416.html

分享给朋友:

“CDN检测器:Python编程实现域名CDN使用情况的检测” 的相关文章

0.Python环境的搭建

0.Python环境的搭建

   请打开网页  https://www.python.org/downloads/windows/    Windows环境下的Python        这里我选择...

Python关于turtle的函数名

Python关于turtle的函数名

turtle.forward(distance)                   向当前画笔方向移动distance像素长度turtle.backward(distance)              向当前画笔相反方向移动distance像素长度turtle.right(degree)    ...

math库的使用

math库的使用

math库包括4个数学常数math.pi      圆周率math.e       自然对数math.inf     正无穷大,负无穷大为-math.infmath.nan     非浮点数标记math库常用函数math.cell(x)      向上取整,返回不小于x的最小整数math.facto...

搜索字符串

搜索字符串

常用搜索字符串中子串的方法str.count(substring)      返回str中substring子串出现的无覆盖的次数str.find(s1)                    返回s1在这个字符串的最低下标,如果字符串中不存在s1,则返回-1str.rfind(s1)       ...

random库

random库

random()            生成一个[0.0,1.0)之间的随机小数randint(a,b)     生成一个[a,b]之间的整数uniform(a,b)     生成一个[a,b]之间的随机小数对random库的引用方法与math库一样,采用下面两种方式实现:import random...

一文快速搞定基本Python

一文快速搞定基本Python

本文适宜有熟练其他高级语言编程基础的同行参阅,或复习用,转载请保留作者信息 Myfpga.cn Chanra1n输入输出#input输入命令,中间的即提示语,左面的a为输入的值存到哪里 a=input("请输入a的值:") #print()可以直接print("He...