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

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

chanra1n1个月前 (04-09)Python286

在介绍这个用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: [email protected]
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发布,如需转载请注明出处。

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

分享给朋友:

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

Python关于turtle的函数名

Python关于turtle的函数名

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

for循环

for循环

range()函数range(start,end,step)range()函数返回一个可迭代对象(可理解为一个序列,序列中的数包括start,不包括end)例如range(1,101),返回1-100的序列。range(101),范围0-100的序列。range(1,100,2),返回1,3,5.....

  索引运算符【】

索引运算符【】

选择字符串的子序列语法【start:finish】        start:子序列开始位置的索引值        finish:子序列结束位置的下一个字符的索引值如果不提供start或者finish,默认start为第一个字符,finish为最后一个字符。例如>>>my_str=...

random库

random库

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

列表作为函数参数

列表作为函数参数

列表作为函数参数,函数中可以修改原列表def multiply(values,factor):     for i in range(len(values)):        values[i]*=factor          aList=[1,2,3,4,5]  multiply(aL...

一文快速搞定基本Python

一文快速搞定基本Python

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