Go / GoLang检查范围内的IP地址 [英] Go/GoLang check IP address in range
本文介绍了Go / GoLang检查范围内的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
216.14.49.184
到 216.14.49.191
,我将如何检查给定的输入IP地址是否在该范围内?解决方案
IP地址表示为bigendian [] byte
go中的切片( IP
类型),所以可以正确比较使用 bytes.Compare
。
( play )
包主要
导入(
字节
fmt
净
)
var(
ip1 = net.ParseIP(216.14.49.184)
ip2 = net.ParseIP(216.14.49.191)
)
func check(ip string) bool {
trial:= net.ParseIP(ip)
if trial.To4()== nil {
fmt.Printf(%v不是IPv4地址\ n,试用)
返回false
}
if byt es.Compare(trial,ip1)> = 0&& bytes.Compare(trial,ip2)<= 0 {
fmt.Printf(%v在%v和%v \ n之间,trial,ip1,ip2)
返回true
fmt.Printf(%v不在%v和%v \ n之间,trial,ip1,ip2)
返回false
}
func main(){
check(1.2.3.4)
check(216.14.49.185)
check(1 :: 16)
}
产生
1.2.3.4不在216.14.49.184和216.14.49.191之间
216.14.49.185在216.14.49.184和216.14.49.191之间
1 :: 16不是IPv4地址
In Go/GoLang, what is the fastest way to check if an IP address is in a specific range?
For example, given range 216.14.49.184
to 216.14.49.191
, how would I check if a given input IP address is in that range?
解决方案
IP addresses are represented as bigendian []byte
slices in go (the IP
type) so will compare correctly using bytes.Compare
.
Eg (play)
package main
import (
"bytes"
"fmt"
"net"
)
var (
ip1 = net.ParseIP("216.14.49.184")
ip2 = net.ParseIP("216.14.49.191")
)
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("1::16")
}
Which produces
1.2.3.4 is NOT between 216.14.49.184 and 216.14.49.191
216.14.49.185 is between 216.14.49.184 and 216.14.49.191
1::16 is not an IPv4 address
这篇关于Go / GoLang检查范围内的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文