Skip to content

Instantly share code, notes, and snippets.

@wuyanxin
Created July 8, 2021 09:10
Show Gist options
  • Save wuyanxin/f452118a9804e0eb1aaf586b8895a545 to your computer and use it in GitHub Desktop.
Save wuyanxin/f452118a9804e0eb1aaf586b8895a545 to your computer and use it in GitHub Desktop.
ip match in golang
type IPMatcher struct {
IP net.IP
SubNet *net.IPNet
}
type IPMatchers []*IPMatcher
func NewIPMatcher(ipStr string) (*IPMatcher, error) {
ip, subNet, err := net.ParseCIDR(ipStr)
if err != nil {
ip = net.ParseIP(ipStr)
if ip == nil {
return nil, errors.New("invalid IP: "+ipStr)
}
}
return &IPMatcher{ip, subNet}, nil
}
func (m IPMatcher) Match(ipStr string) bool {
ip := net.ParseIP(ipStr)
if ip == nil {
return false
}
return m.IP.Equal(ip) || m.SubNet != nil && m.SubNet.Contains(ip)
}
func NewIPMatchers(ips []string) (list IPMatchers, err error) {
for _, ipStr := range ips {
var m *IPMatcher
m, err = NewIPMatcher(ipStr)
if err != nil {
return
}
list = append(list, m)
}
return
}
func IPContains(ipMatchers []*IPMatcher, ip string) bool {
for _, m := range ipMatchers {
if m.Match(ip) {
return true
}
}
return false
}
func (ms IPMatchers) Match(ip string) bool {
return IPContains(ms, ip)
}
package utils
import "testing"
func TestIPMatcher(t *testing.T) {
a, errA := NewIPMatcher("127.0.0.1")
if errA != nil {
t.Error(errA)
}
if a.IP.String() != "127.0.0.1" || a.SubNet != nil {
t.Error("ip parse error")
}
b, errB := NewIPMatcher("192.168.1.1/24")
if errB != nil {
t.Error(errB)
}
if b.IP.String() != "192.168.1.1" || b.SubNet == nil {
t.Errorf("ip match error: %s, %v", b.IP.String(), b.SubNet)
}
if !b.Match("192.168.1.1") || !b.Match("192.168.1.2") {
t.Error("ip match error")
}
}
func TestIPMatchers(t *testing.T) {
var WhiteListIPs = []string{"127.0.0.1", "192.168.1.0/24", "10.1.0.0/16"}
M, err := NewIPMatchers(WhiteListIPs)
if err != nil {
t.Error(err)
}
if !M.Match("127.0.0.1") || !M.Match("192.168.1.1") || !M.Match("192.168.1.199") ||
!M.Match("10.1.0.1") || !M.Match("10.1.3.1") {
t.Error("ip match error")
}
if M.Match("127.0.0.2") || M.Match("192.168.2.1") || M.Match("10.2.0.1") {
t.Error("ip match error 2")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment