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

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

chanra1n3周前 (04-09)Python214

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

本文链接:https://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'...

2.Python中的基本运算

2.Python中的基本运算

我们打开Python,请你尝试输入如下算式并尝试理解有什么为什么是这样的?1+1 1+1.0 1-2 2-3.5 1*1 1*1.1 1/2 2/1 2/3 3/2 3//2 3/1.0 5/2.5我们不难得到如下结果2 2.0 -1 -1.5 1 1.1 0.5...

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.....

列表实例

列表实例

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

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

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

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

(原创)使用Python对任意网站图片进行爬取,仅用于学习

(原创)使用Python对任意网站图片进行爬取,仅用于学习

import os import time import argparse import requests import re import io from urllib.parse import ...