網站需依訪客 IP 判斷運營商 (電信/網通) 以實現智能解析、流量統計或差異化服務。傳統做法查詢 IP 資料庫 (如 ip2location),但每次查詢需磁碟 I/O 或資料庫連線,效能不足。本文介紹一種預載入記憶體、O(1) 查表的極速演算法。
中國網通 (CNC) 路由表中,最長遮罩為 /24 (255.255.255.0),即最小網段包含 256 個 IP。因此 IP 最後一個八位組可忽略,僅以前三段 (24 bits) 作為 Key。
Index = (A * 65536 + B * 256 + C) / 8 ' Byte 位置
BitPos = (A * 65536 + B * 256 + C) Mod 8 ' Byte 內第幾 bit
' A.B.C 為 IP 前三段
cnc.txt (網通路由表),每行格式:123.0.0.0/24 或 202.0.0.0/16cnc.dat 放在網站目錄<% ' global.asa
Sub Application_OnStart
Call InitCNCBuffer()
End Sub
Sub InitCNCBuffer()
Dim stream
Set stream = Server.CreateObject("ADODB.Stream")
stream.Type = 1 ' adTypeBinary
stream.Open
stream.LoadFromFile Server.MapPath("cnc.dat")
Application("cnc") = stream.Read
stream.Close
Set stream = Nothing
End Sub
%>
<%
Function IsCNC(ip)
Dim parts, idx, byteVal, bitMask
parts = Split(ip, ".")
If UBound(parts) <> 3 Then Exit Function ' 非標準 IPv4
' 計算線性索引 (前三段)
idx = CLng(parts(0)) * 65536 + CLng(parts(1)) * 256 + CLng(parts(2))
' 定位 Byte 與 Bit
byteVal = AscB(MidB(Application("cnc"), idx \ 8 + 1, 1))
bitMask = 2 ^ (idx Mod 8)
IsCNC = (byteVal And bitMask) <> 0
End Function
%>
<%@ Language=VBScript %>
<!--#include file="global.asa"--> ' 確保 Application("cnc") 已載入
<%
Dim clientIP, isCNC
clientIP = Request.ServerVariables("REMOTE_ADDR")
isCNC = IsCNC(clientIP)
If isCNC Then
Response.Write clientIP & " 屬於中國網通 (CNC)"
Else
Response.Write clientIP & " 屬於中國電信 (或其他)"
End If
%>
| 指標 | 數值 |
|---|---|
| 記憶體佔用 | ~2 MB (Application 物件) |
| 查詢時間 | < 0.1 ms (純記憶體位運算) |
| 首次載入 | ~50 ms (讀取 2MB 檔案) |
| 支援 IPv6 | 否 (需擴充) |