IsBrow)。Iplist.txt)比對 IP。<%
'/////////////////////////////////////////////////////
' 作用:一個 IP 地址只允許瀏覽本頁一次
' 作者: BaCde 2010-03-01
' 引用:<!-- #include file="Check_Ip.asp" -->
'/////////////////////////////////////////////////////
Dim Fso, ts, IpList, Cfs
' 設定 Cookie(一年有效)
Function SetCookie()
Response.Cookies("IsBrow") = "Brow"
Response.Cookies("IsBrow").Expires = Date + 365
End Function
' 記錄 IP 到文字檔
Function WriteIp(FileName, IpAddress)
Set Fso = Server.CreateObject("Scripting.FileSystemObject")
Set ts = Fso.OpenTextFile(Server.MapPath(FileName), 8, True) ' 8=ForAppending
ts.WriteLine IpAddress
ts.Close
Set ts = Nothing
Set Fso = Nothing
End Function
' 讀取 IP 清單
Function ReadIpList(FileName)
Set Fso = Server.CreateObject("Scripting.FileSystemObject")
If Not Fso.FileExists(Server.MapPath(FileName)) Then
CreateFile "Iplist.txt"
Exit Function
End If
Set ts = Fso.OpenTextFile(Server.MapPath(FileName))
IpList = ts.ReadAll
ts.Close
Set ts = Nothing
Set Fso = Nothing
ReadIpList = IpList
End Function
' 建立空文字檔
Function CreateFile(FileName)
Set Fso = Server.CreateObject("Scripting.FileSystemObject")
Set Cfs = Fso.CreateTextFile(Server.MapPath(FileName))
Cfs.Close
Set Cfs = Nothing
Set Fso = Nothing
End Function
'========== 主程式進入點 ==========
Dim clientIP, ipListContent
clientIP = Request.ServerVariables("REMOTE_ADDR")
' 1. 檢查 Cookie
If Request.Cookies("IsBrow") = "Brow" Then
Response.Write ""
Response.End
End If
' 2. 檢查伺服器端 IP 清單
ipListContent = ReadIpList("Iplist.txt")
If InStr(ipListContent, clientIP) > 0 Then
Response.Write ""
Response.End
End If
' 3. 通過檢查:記錄 IP、設定 Cookie
WriteIp "Iplist.txt", clientIP
SetCookie
%>
在需保護的頁面最頂端引入:
<!-- #include file="Check_Ip.asp" -->
| 優點 | 缺點 | 改進方向 |
|---|---|---|
| 部署簡單,無需資料庫 | 文字檔隨訪客增長,查詢效能下降 | 改用 Application 變數或資料庫儲存 IP |
| 雙重檢查 | Cookie 可被使用者清除/封鎖 | 結合 Session 或指紋辨識 |
| 原始碼可讀性高 | 無法防禦代理/NAT 共用 IP | 結合 User-Agent、Header 特徵判斷 |
Application.Lock/Unlock 同步寫入 Application 變數陣列,避免文字檔 I/O 瓶頸。