当前位置:首页 > 问答 > 正文

ASP编程 域名解析 如何用ASP代码高效提取URL中的顶级域名

🚀 ASP提取顶级域名大法 🚀
(信息更新至2025年8月,附代码+emoji趣味讲解)

ASP编程 域名解析 如何用ASP代码高效提取URL中的顶级域名

🎯 核心逻辑

通过拆分主机名 + 匹配顶级域名库,高效提取URL中的顶级域名!
步骤拆解
1️⃣ 获取主机名Request.ServerVariables("HTTP_HOST")
2️⃣ 拆分为主机数组:按分割域名部分
3️⃣ 优先匹配二级顶级域名(如co.ukgov.cn
4️⃣ 再匹配单字顶级域名(如comcn
5️⃣ 保底方案:取最后一个部分(如uk

💻 ASP代码示例

<%
' 🌐 获取并处理主机名
Dim hostName, hostParts, tld
hostName = LCase(Request.ServerVariables("HTTP_HOST"))
hostParts = Split(hostName, ".")
' 📚 顶级域名库(需手动维护)
Dim tldList, tldList2
tldList = Array("com","net","org","uk","cn","jp","info","biz","co","ac")
tldList2 = Array("co.uk","gov.uk","com.cn","net.cn","org.cn") ' 二级域名
' 🔍 优先匹配二级域名
For i = UBound(hostParts) To 1 Step -1
    Dim combined
    combined = hostParts(i-1) & "." & hostParts(i)
    If InArray(combined, tldList2) Then
        tld = combined
        Exit For
    End If
Next
' 🔍 再匹配单字域名
If tld = "" Then
    For i = UBound(hostParts) To 0 Step -1
        If InArray(hostParts(i), tldList) Then
            tld = hostParts(i)
            Exit For
        End If
    Next
End If
' 🎯 保底方案
If tld = "" And UBound(hostParts) >=0 Then tld = hostParts(UBound(hostParts))
Response.Write "🌍 顶级域名:" & tld
' 🛠 辅助函数:数组包含检查
Function InArray(element, arr)
    Dim i
    For i = 0 To UBound(arr)
        If arr(i) = element Then InArray = True : Exit Function
    Next
    InArray = False
End Function
%>

🧪 测试用例

URL 输出结果 说明
http://www.abc.com 🌍 com 匹配单字顶级域名
http://x.y.co.uk 🌍 co.uk 匹配二级域名库
http://site.gov.cn 🌍 gov.cn 匹配二级域名库
http://a.b.c.jp 🌍 jp 匹配单字顶级域名

📌 注意事项

  1. 域名库需定期更新:新增顶级域名(如.ai.xyz)需手动加入列表。
  2. 性能优化:将域名库存入Application变量,避免重复加载。
  3. 特殊场景:如blogspot.com类域名,需额外处理子域名逻辑。

💡 进阶建议:结合正则表达式或调用公共DNS API,实现更智能的域名解析!

ASP编程 域名解析 如何用ASP代码高效提取URL中的顶级域名

发表评论