Monday, May 2, 2022

[Golang] 檢查IP 是否在特定範圍內的簡單範例

檢查IP 是否在特定範圍內,的最快方法是什麼?例如,給定範圍192.168.1.1至192.168.10.254,如何檢查給定的輸入IP是否在該範圍內?以下是簡單範例:

package main

import (
    "bytes"
    "fmt"
    "net"
)

var (
    ip1 = net.ParseIP("192.168.1.1")
    ip2 = net.ParseIP("192.168.10.254")
)

func check(ip string) bool {
    trial := net.ParseIP(ip)
    if trial.To4() == nil {
        fmt.Printf("%v is not an IPv4 address\n", trial)
        return false
    }
    if bytes.Compare(trial, ip1) >= 0 && bytes.Compare(trial, ip2) <= 0 {
        fmt.Printf("%v is between %v and %v\n", trial, ip1, ip2)
        return true
    }
    fmt.Printf("%v is NOT between %v and %v\n", trial, ip1, ip2)
    return false
}

func main() {
    check("1.2.3.4")
    check("216.14.49.185")
    check("192.168.3.3")
    check("1::16")
}

Result:

1.2.3.4 is NOT between 192.168.1.1 and 192.168.10.254 216.14.49.185 is NOT between 192.168.1.1 and 192.168.10.254 192.168.3.3 is between 192.168.1.1 and 192.168.10.254 1::16 is not an IPv4 address

https://stackoverflow.com/questions/19882961/go-golang-check-ip-address-in-range


No comments: