go ip过滤_Go / GoLang检查范围内的IP地址

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值