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

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

chanra1n3周前 (04-09)Python199

在介绍这个用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使用情况的检测” 的相关文章

1.Python基本的使用

1.Python基本的使用

我们打开python或者通过运行python也可以,请复制如下代码,然后按下Enter键,看看会发生什么?print('\n'.join([''.join([('MyFpga'[(x-y) % len('MyFpga'...

Python关于turtle的函数名

Python关于turtle的函数名

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

  索引运算符【】

索引运算符【】

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

列表实例

列表实例

随机生成100个小写字母存入一个列表中,统计26个字母的出现次数。import random def getRandomLetter():     code_a=ord('a')     code_z=ord('z')     x=random.randint(code_a,code_z)...

anaconda打不开的解决方法

anaconda打不开的解决方法

报错内容Navigator Error An unexpected error occurred on Navigator start-up Report Please report this ...

Python自动清理错误图片,深度学习训练数据集准备

Python自动清理错误图片,深度学习训练数据集准备

使用python运行from PIL import Image from pathlib import Path import os   path = r'.'  ...