sample code to check that ip in specific cidr range

1,663 views
Skip to first unread message

Vasiliy Tolstov

unread,
Feb 21, 2012, 3:42:55 AM2/21/12
to golang-nuts
Hello. Can somebody share code to check that specific ip belongs to
specific cidr block?
I have some nets and want to do some stuff for local clients and
another for non local...

--
Vasiliy Tolstov,
Clodo.ru
e-mail: v.to...@selfip.ru
jabber: va...@selfip.ru

Dustin

unread,
Feb 21, 2012, 4:04:31 AM2/21/12
to golan...@googlegroups.com
It looks like the net package does it all for you.



package main

import (
"net"
"testing"
)

type item struct {
addr    string
cidr    string
matches bool
}

var testdata = []item{
item{"192.168.1.67", "192.168.1.0/24", true},
item{"192.168.1.67", "192.168.1.0/28", false},
item{"192.168.1.67", "0.0.0.0/0", true},
}

func TestCIDRMatch(t *testing.T) {
for _, it := range testdata {
_, cidrnet, err := net.ParseCIDR(it.cidr)
if err != nil {
panic(err) // assuming I did it right above
}
myaddr := net.ParseIP(it.addr)
if cidrnet.Contains(myaddr) != it.matches {
t.Fatalf("Wrong on %+v")
}
}
}

Vasiliy Tolstov

unread,
Feb 22, 2012, 1:32:25 AM2/22/12
to Dustin, golan...@googlegroups.com
2012/2/21 Dustin <dsal...@gmail.com>:

> It looks like the net package does it all for you.
>
>
>

Thanks!

Reply all
Reply to author
Forward
0 new messages