Go 中高效率檢查某個範圍內的IP 位址
判斷IP 位址是否在指定範圍內是各種網路中的常見需求運作。在 Go 中,有多種方法可以解決此任務。
最快方法:bytes.Compare
最有效的方法之一是使用 bytes.Compare 函數比較 IP 位址的位元組表示。
import ( "bytes" "net" ) // Check if an IP address is within a range func check(trial, start, end net.IP) bool { if start.To4() == nil || end.To4() == nil || trial.To4() == nil { return false } return bytes.Compare(trial, start) >= 0 && bytes.Compare(trial, end) <= 0 }
在這種方法中,我們首先檢查給定的 IP 位址是否是有效的 IPv4位址。然後,我們使用 bytes.Compare 來比較試驗 IP 的位元組表示以及範圍的起點和終點。若兩次檢查的比較結果均為非負值,則表示 IP 位址在範圍內。
使用示例
以下代碼演示了bytes.Compare 方法的用法:
import ( "fmt" "net" ) var ( ip1 = net.ParseIP("216.14.49.184") ip2 = net.ParseIP("216.14.49.191") ) func main() { check := func(ip string) { trial := net.ParseIP(ip) res := check(trial, ip1, ip2) fmt.Printf("%v is %v within range %v to %v\n", trial, res, ip1, ip2) } check("1.2.3.4") check("216.14.49.185") check("216.14.49.191") }
輸出:
1.2.3.4 is false within range 216.14.49.184 to 216.14.49.191 216.14.49.185 is true within range 216.14.49.184 to 216.14.49.191 216.14.49.191 is true within range 216.14.49.184 to 216.14.49.191
以上是Go中如何有效率地檢查IP位址是否在某個範圍內?的詳細內容。更多資訊請關注PHP中文網其他相關文章!