Golang CIDRMask示例

说明

golang cidrmask示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: net

示例#1
文件: setup_fixedcidrv4_test.go 项目: choldrim/docker

func TestSetupFixedCIDRv4(t *testing.T) {
	defer netutils.SetupTestNetNS(t)()

	config := &NetworkConfiguration{
		BridgeName:  DefaultBridgeName,
		AddressIPv4: &net.IPNet{IP: net.ParseIP("192.168.1.1"), Mask: net.CIDRMask(16, 32)},
		FixedCIDR:   &net.IPNet{IP: net.ParseIP("192.168.2.0"), Mask: net.CIDRMask(24, 32)}}
	br := &bridgeInterface{}

	if err := setupDevice(config, br); err != nil {
		t.Fatalf("Bridge creation failed: %v", err)
	}
	if err := setupBridgeIPv4(config, br); err != nil {
		t.Fatalf("Assign IPv4 to bridge failed: %v", err)
	}

	if err := setupFixedCIDRv4(config, br); err != nil {
		t.Fatalf("Failed to setup bridge FixedCIDRv4: %v", err)
	}

	if ip, err := ipAllocator.RequestIP(config.FixedCIDR, nil); err != nil {
		t.Fatalf("Failed to request IP to allocator: %v", err)
	} else if expected := "192.168.2.1"; ip.String() != expected {
		t.Fatalf("Expected allocated IP %s, got %s", expected, ip)
	}
}

示例#2
文件: options_test.go 项目: NeilW/cni

func validateRoutes(t *testing.T, routes []plugin.Route) {
	expected := []plugin.Route{
		plugin.Route{
			Dst: net.IPNet{
				IP:   net.IPv4(10, 0, 0, 0),
				Mask: net.CIDRMask(8, 32),
			},
			GW: net.IPv4(10, 1, 2, 3),
		},
		plugin.Route{
			Dst: net.IPNet{
				IP:   net.IPv4(192, 168, 1, 0),
				Mask: net.CIDRMask(24, 32),
			},
			GW: net.IPv4(192, 168, 2, 3),
		},
	}

	if len(routes) != len(expected) {
		t.Fatalf("wrong length slice; expected %v, got %v", len(expected), len(routes))
	}

	for i := 0; i < len(routes); i++ {
		a := routes[i]
		e := expected[i]

		if a.Dst.String() != e.Dst.String() {
			t.Errorf("route.Dst mismatch: expected %v, got %v", e.Dst, a.Dst)
		}

		if !a.GW.Equal(e.GW) {
			t.Errorf("route.GW mismatch: expected %v, got %v", e.GW, a.GW)
		}
	}
}

示例#3
文件: proxy.go 项目: KarolBedkowski/secproxy

func prepareNetworks(addrs string) (networks []*net.IPNet) {
	for _, n := range strings.Fields(addrs) {
		n = strings.TrimSpace(n)
		if strings.Contains(n, "/") {
			if _, network, err := net.ParseCIDR(n); err == nil {
				networks = append(networks, network)
			} else {
				log.Warn("authenticationMW prepare networks error", "err", err, "net", n)
			}
		} else {
			if ip := net.ParseIP(n); ip != nil {
				var mask net.IPMask
				if len(ip) == 4 { // ipv4
					mask = net.CIDRMask(32, 32)
				} else {
					mask = net.CIDRMask(128, 128)
				}
				network := &net.IPNet{ip, mask}
				networks = append(networks, network)
			} else {
				log.Warn("authenticationMW prepare ip error", "net", n)
			}
		}
	}
	log.Debug("prepareNetworks", "networks", networks, "inp", addrs)
	return
}

示例#4
文件: setup_fixedcidrv4_test.go 项目: choldrim/docker

func TestSetupBadFixedCIDRv4(t *testing.T) {
	defer netutils.SetupTestNetNS(t)()

	config := &NetworkConfiguration{
		BridgeName:  DefaultBridgeName,
		AddressIPv4: &net.IPNet{IP: net.ParseIP("192.168.1.1"), Mask: net.CIDRMask(24, 32)},
		FixedCIDR:   &net.IPNet{IP: net.ParseIP("192.168.2.0"), Mask: net.CIDRMask(24, 32)}}
	br := &bridgeInterface{}

	if err := setupDevice(config, br); err != nil {
		t.Fatalf("Bridge creation failed: %v", err)
	}
	if err := setupBridgeIPv4(config, br); err != nil {
		t.Fatalf("Assign IPv4 to bridge failed: %v", err)
	}

	err := setupFixedCIDRv4(config, br)
	if err == nil {
		t.Fatal("Setup bridge FixedCIDRv4 should have failed")
	}

	if _, ok := err.(*FixedCIDRv4Error); !ok {
		t.Fatalf("Did not fail with expected error. Actual error: %v", err)
	}

}

示例#5
文件: xfrm_linux.go 项目: CadeLaRen/docker-3

func (x *XfrmAddress) ToIPNet(prefixlen uint8) *net.IPNet {
	ip := x.ToIP()
	if GetIPFamily(ip) == FAMILY_V4 {
		return &net.IPNet{IP: ip, Mask: net.CIDRMask(int(prefixlen), 32)}
	}
	return &net.IPNet{IP: ip, Mask: net.CIDRMask(int(prefixlen), 128)}
}

示例#6
文件: edns.go 项目: Rudloff/platform

func (e *EDNS0_SUBNET) pack() ([]byte, error) {
	b := make([]byte, 4)
	binary.BigEndian.PutUint16(b[0:], e.Family)
	b[2] = e.SourceNetmask
	b[3] = e.SourceScope
	switch e.Family {
	case 1:
		if e.SourceNetmask > net.IPv4len*8 {
			return nil, errors.New("dns: bad netmask")
		}
		if len(e.Address.To4()) != net.IPv4len {
			return nil, errors.New("dns: bad address")
		}
		ip := e.Address.To4().Mask(net.CIDRMask(int(e.SourceNetmask), net.IPv4len*8))
		needLength := (e.SourceNetmask + 8 - 1) / 8 // division rounding up
		b = append(b, ip[:needLength]...)
	case 2:
		if e.SourceNetmask > net.IPv6len*8 {
			return nil, errors.New("dns: bad netmask")
		}
		if len(e.Address) != net.IPv6len {
			return nil, errors.New("dns: bad address")
		}
		ip := e.Address.Mask(net.CIDRMask(int(e.SourceNetmask), net.IPv6len*8))
		needLength := (e.SourceNetmask + 8 - 1) / 8 // division rounding up
		b = append(b, ip[:needLength]...)
	default:
		return nil, errors.New("dns: bad address family")
	}
	return b, nil
}

示例#7
文件: status.go 项目: levenlabs/go-openvpn

// parseRouteAddr parses a string route address and returns the resulting
// RouteAddr struct
func parseRouteAddr(text string) (RouteAddr, error) {
	r := RouteAddr{}
	// detect if this is a remote addr
	if strings.HasSuffix(text, "C") {
		text = strings.TrimSuffix(text, "C")
		r.Remote = true
	}
	// for some reason ipm.IP is 16 bytes for an IPv4, but ip is 4 bytes
	// so we use ip instead
	ip, ipm, err := net.ParseCIDR(text)
	if err == nil {
		r.IP = ip
		r.Mask = ipm.Mask
		return r, nil
	}

	//it might not be a CIDR and instead just an IP
	r.IP = net.ParseIP(text)
	if r.IP == nil {
		return r, err
	}

	r.Mask = net.CIDRMask(32, 8*net.IPv4len)
	if r.IP.To4() == nil {
		r.Mask = net.CIDRMask(128, 8*net.IPv6len)
	}
	return r, nil
}

示例#8
文件: compare.go 项目: ably-forks/flynn

func (c *CIDRs) UnmarshalBinary(b []byte) error {
	if len(b) < 1 {
		return fmt.Errorf("compare: missing type byte")
	}
	if b[0] != byte(TypeCIDRs) {
		return fmt.Errorf("compare: expected type %d, got %d", TypeCIDRs, b[0])
	}
	b = b[1:]
	*c = make(CIDRs, 0, len(b)/ipv4CIDRLen)
	for len(b) > 0 {
		var n net.IPNet
		if b[0]&(1<<7) == 0 { // check top bit of ones byte, if 0, IPv4, if 1, IPv6
			if len(b) < ipv4CIDRLen {
				return fmt.Errorf("compare: unexpected end of buffer decoding IPv4 CIDR")
			}
			n.Mask = net.CIDRMask(int(b[0]), ipv4Len*8)
			n.IP = net.IPv4(b[1], b[2], b[3], b[4])
			b = b[5:]
		} else {
			if len(b) < ipv6CIDRLen {
				return fmt.Errorf("compare: unexpected end of buffer decoding IPv6 CIDR")
			}
			n.Mask = net.CIDRMask(int(b[0]&^(1<<7)), ipv6Len*8)
			n.IP = make([]byte, ipv6Len)
			copy(n.IP, b[1:])
			b = b[ipv6CIDRLen:]
		}
		*c = append(*c, n)
	}
	return nil
}

示例#9
文件: ptp.go 项目: sinfomicien/rkt

func setupHostVeth(vethName string, ipConf *types.IPConfig) error {
	// hostVeth moved namespaces and may have a new ifindex
	veth, err := netlink.LinkByName(vethName)
	if err != nil {
		return fmt.Errorf("failed to lookup %q: %v", vethName, err)
	}

	// TODO(eyakubovich): IPv6
	ipn := &net.IPNet{
		IP:   ipConf.Gateway,
		Mask: net.CIDRMask(32, 32),
	}
	addr := &netlink.Addr{IPNet: ipn, Label: ""}
	if err = netlink.AddrAdd(veth, addr); err != nil {
		return fmt.Errorf("failed to add IP addr (%#v) to veth: %v", ipn, err)
	}

	ipn = &net.IPNet{
		IP:   ipConf.IP.IP,
		Mask: net.CIDRMask(32, 32),
	}
	// dst happens to be the same as IP/net of host veth
	if err = ip.AddHostRoute(ipn, nil, veth); err != nil && !os.IsExist(err) {
		return fmt.Errorf("failed to add route on host: %v", err)
	}

	return nil
}

示例#10
文件: rule_test.go 项目: winsx/libnetwork

func TestRuleAddDel(t *testing.T) {
	srcNet := &net.IPNet{IP: net.IPv4(172, 16, 0, 1), Mask: net.CIDRMask(16, 32)}
	dstNet := &net.IPNet{IP: net.IPv4(172, 16, 1, 1), Mask: net.CIDRMask(24, 32)}

	rules_begin, err := RuleList(syscall.AF_INET)
	if err != nil {
		t.Fatal(err)
	}

	rule := NewRule()
	rule.Table = syscall.RT_TABLE_MAIN
	rule.Src = srcNet
	rule.Dst = dstNet
	rule.Priority = 5
	rule.OifName = "lo"
	rule.IifName = "lo"
	if err := RuleAdd(rule); err != nil {
		t.Fatal(err)
	}

	rules, err := RuleList(syscall.AF_INET)
	if err != nil {
		t.Fatal(err)
	}

	if len(rules) != len(rules_begin)+1 {
		t.Fatal("Rule not added properly")
	}

	// find this rule
	var found bool
	for i := range rules {
		if rules[i].Table == rule.Table &&
			rules[i].Src != nil && rules[i].Src.String() == srcNet.String() &&
			rules[i].Dst != nil && rules[i].Dst.String() == dstNet.String() &&
			rules[i].OifName == rule.OifName &&
			rules[i].Priority == rule.Priority &&
			rules[i].IifName == rule.IifName {
			found = true
		}
	}
	if !found {
		t.Fatal("Rule has diffrent options than one added")
	}

	if err := RuleDel(rule); err != nil {
		t.Fatal(err)
	}

	rules_end, err := RuleList(syscall.AF_INET)
	if err != nil {
		t.Fatal(err)
	}

	if len(rules_end) != len(rules_begin) {
		t.Fatal("Rule not removed properly")
	}
}

示例#11
文件: parser.go 项目: zaccone/goSPF

func splitToHostNetwork(domain string) (bool, string, *net.IPMask, *net.IPMask) {
	var host string

	const v4Len = 32
	n4s := "32"

	const v6Len = 128
	n6s := "128"

	line := strings.SplitN(domain, "/", 3)
	if len(line) == 3 {
		host, n4s, n6s = line[0], line[1], line[2]
	} else if len(line) == 2 {
		host, n4s = line[0], line[1]
	} else {
		host = line[0]
	}

	if !IsDomainName(host) {
		return false, host, nil, nil
	}

	if isEmpty(&n4s) {
		// empty values default to maximum netmask
		n4s = "32"
	}

	if isEmpty(&n6s) {
		// empty values default to maximum netmask
		n6s = "128"
	}

	var err error
	var n4 int
	var n6 int

	var v4Network net.IPMask
	var v6Network net.IPMask

	if n4, err = strconv.Atoi(n4s); err != nil {
		return false, host, nil, nil
	} else if n4 < 0 || n4 > v4Len {
		return false, host, nil, nil
	} else {
		v4Network = net.CIDRMask(n4, v4Len)
	}

	if n6, err = strconv.Atoi(n6s); err != nil {
		return false, host, nil, nil
	} else if n6 < 0 || n6 > v6Len {
		return false, host, nil, nil
	} else {
		v6Network = net.CIDRMask(n6, v6Len)
	}

	return true, host, &v4Network, &v6Network

}

示例#12
文件: context_test.go 项目: vmware/vic

func testConfig() *Configuration {
	return &Configuration{
		source:     extraconfig.MapSource(map[string]string{}),
		sink:       extraconfig.MapSink(map[string]string{}),
		BridgeLink: &mockLink{},
		Network: config.Network{
			BridgeNetwork: "bridge",
			ContainerNetworks: map[string]*executor.ContainerNetwork{
				"bridge": {
					Common: executor.Common{
						Name: "bridge",
					},
					Type: constants.BridgeScopeType,
				},
				"bar7": {
					Common: executor.Common{
						Name: "external",
					},
					Gateway:     net.IPNet{IP: net.ParseIP("10.13.0.1"), Mask: net.CIDRMask(16, 32)},
					Nameservers: []net.IP{net.ParseIP("10.10.1.1")},
					Pools:       []ip.Range{*ip.ParseRange("10.13.1.0-255"), *ip.ParseRange("10.13.2.0-10.13.2.15")},
					Type:        constants.ExternalScopeType,
				},
				"bar71": {
					Common: executor.Common{
						Name: "external",
					},
					Gateway:     net.IPNet{IP: net.ParseIP("10.131.0.1"), Mask: net.CIDRMask(16, 32)},
					Nameservers: []net.IP{net.ParseIP("10.131.0.1"), net.ParseIP("10.131.0.2")},
					Pools:       []ip.Range{*ip.ParseRange("10.131.1.0/16")},
					Type:        constants.ExternalScopeType,
				},
				"bar72": {
					Common: executor.Common{
						Name: "external",
					},
					Type: constants.ExternalScopeType,
				},
				"bar73": {
					Common: executor.Common{
						Name: "external",
					},
					Gateway: net.IPNet{IP: net.ParseIP("10.133.0.1"), Mask: net.CIDRMask(16, 32)},
					Type:    constants.ExternalScopeType,
				},
			},
		},
		PortGroups: map[string]object.NetworkReference{
			"bridge": testBridgeNetwork,
			"bar7":   testExternalNetwork,
			"bar71":  testExternalNetwork,
			"bar72":  testExternalNetwork,
			"bar73":  testExternalNetwork,
		},
	}
}

示例#13
文件: context_test.go 项目: kjplatz/vic

func TestMain(m *testing.M) {
	n := object.NewNetwork(nil, types.ManagedObjectReference{})
	n.InventoryPath = "testBridge"
	testBridgeNetwork = n

	n = object.NewNetwork(nil, types.ManagedObjectReference{})
	n.InventoryPath = "testExternal"
	testExternalNetwork := n

	Config = Configuration{
		BridgeLink:    &mockLink{},
		BridgeNetwork: "bridge",
		ContainerNetworks: map[string]*ContainerNetwork{
			"bridge": &ContainerNetwork{
				PortGroup: testBridgeNetwork,
			},
			"bar7": &ContainerNetwork{
				Common: executor.Common{
					Name: "external",
				},
				Gateway:     net.IPNet{IP: net.ParseIP("10.13.0.1"), Mask: net.CIDRMask(16, 32)},
				Nameservers: []net.IP{net.ParseIP("10.10.1.1")},
				Pools:       []ip.Range{*ip.ParseRange("10.13.1.0-255"), *ip.ParseRange("10.13.2.0-10.13.2.15")},
				PortGroup:   testExternalNetwork,
			},
			"bar71": &ContainerNetwork{
				Common: executor.Common{
					Name: "external",
				},
				Gateway:     net.IPNet{IP: net.ParseIP("10.131.0.1"), Mask: net.CIDRMask(16, 32)},
				Nameservers: []net.IP{net.ParseIP("10.131.0.1"), net.ParseIP("10.131.0.2")},
				Pools:       []ip.Range{*ip.ParseRange("10.131.1.0/16")},
				PortGroup:   testExternalNetwork,
			},
			"bar72": &ContainerNetwork{
				Common: executor.Common{
					Name: "external",
				},
				PortGroup: testExternalNetwork,
			},
			"bar73": &ContainerNetwork{
				Common: executor.Common{
					Name: "external",
				},
				Gateway:   net.IPNet{IP: net.ParseIP("10.133.0.1"), Mask: net.CIDRMask(16, 32)},
				PortGroup: testExternalNetwork,
			},
		},
	}

	rc := m.Run()

	os.Exit(rc)
}

示例#14
文件: dnsmasq.go 项目: hanscj1/mantle

func newInterface(s, i byte) *Interface {
	return &Interface{
		HardwareAddr: net.HardwareAddr{0x02, s, 0, 0, 0, i},
		DHCPv4: []net.IPNet{{
			IP:   net.IP{10, s, 0, i},
			Mask: net.CIDRMask(24, 32)}},
		DHCPv6: []net.IPNet{{
			IP:   net.IP{0xfd, s, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, i},
			Mask: net.CIDRMask(64, 128)}},
	}
}

示例#15
文件: example_test.go 项目: Harvey-OS/go

func ExampleCIDRMask() {
	// This mask corresponds to a /31 subnet for IPv4.
	fmt.Println(net.CIDRMask(31, 32))

	// This mask corresponds to a /64 subnet for IPv6.
	fmt.Println(net.CIDRMask(64, 128))

	// Output:
	// fffffffe
	// ffffffffffffffff0000000000000000
}

示例#16
文件: addr_range_test.go 项目: jddixon/xlOverlay_go

func (s *XLSuite) TestAddrRangeCtor(c *C) {
	rng := xr.MakeSimpleRNG()

	// v4 address ---------------------------------------------------
	v4PLen := uint(1 + rng.Intn(32)) // in bits
	v4ByteLen := 4                   // ((v4PLen + 7) / 8) * 8
	pBuffer := make([]byte, v4ByteLen)
	rng.NextBytes(pBuffer)
	cidrMask := net.CIDRMask(int(v4PLen), 32)
	for i := 0; i < 4; i++ {
		pBuffer[i] &= cidrMask[i]
	}
	p, err := NewV4AddrRange(pBuffer, v4PLen)
	c.Assert(err, IsNil)
	c.Assert(p, Not(IsNil))

	//        actual          vs    expected
	c.Assert(p.PrefixLen(), Equals, v4PLen)
	c.Assert(p.AddrLen(), Equals, uint(32))

	// very weak tests of Equal()
	c.Assert(p.Equal(p), Equals, true)
	c.Assert(p.Equal(nil), Equals, false)

	// a better implementation would truncate the prefix to the right
	// number of bits; a better test would test whether the truncation
	// is done correctly

	// v6 address ---------------------------------------------------
	v6PLen := uint(1 + rng.Intn(128)) // in bits
	v6ByteLen := 16                   // ((v6PLen + 7) / 8) * 8
	p6Buffer := make([]byte, v6ByteLen)
	rng.NextBytes(p6Buffer)
	cidrMask = net.CIDRMask(int(v4PLen), 128)
	for i := 0; i < 16; i++ {
		p6Buffer[i] &= cidrMask[i]
	}
	p6, err := NewV6AddrRange(p6Buffer, v6PLen)
	c.Assert(err, IsNil)
	c.Assert(p, Not(IsNil))

	//        actual          vs    expected
	c.Assert(p6.PrefixLen(), Equals, v6PLen)
	c.Assert(p6.AddrLen(), Equals, uint(128))

	// very weak tests of Equal()
	c.Assert(p6.Equal(p6), Equals, true)
	c.Assert(p6.Equal(nil), Equals, false)

	// v4 vs v6 -----------------------------------------------------
	c.Assert(p6.Equal(p), Equals, false)

}

示例#17
文件: peermap.go 项目: ypie/chihaya

func (pm *PeerMap) mask(ip net.IP) string {
	if !pm.Config.PreferredSubnet {
		return ""
	}

	var maskedIP net.IP
	if len(ip) == net.IPv6len {
		maskedIP = ip.Mask(net.CIDRMask(pm.Config.PreferredIPv6Subnet, 128))
	} else {
		maskedIP = ip.Mask(net.CIDRMask(pm.Config.PreferredIPv4Subnet, 32))
	}

	return maskedIP.String()
}

示例#18
文件: util_test.go 项目: Cepave/lvs-metrics

func newTestHost(offset int, shortname string, ipv4, ipv6 bool) Host {
	var h Host
	if shortname != "" {
		h.Hostname = fmt.Sprintf("%s.example.com", shortname)
	}
	if ipv4 {
		h.IPv4Addr = net.ParseIP(fmt.Sprintf("1.2.3.%d", 4+offset))
		h.IPv4Mask = net.CIDRMask(24, 32)
	}
	if ipv6 {
		h.IPv6Addr = net.ParseIP(fmt.Sprintf("2012::%x", 0xcafe+offset))
		h.IPv6Mask = net.CIDRMask(64, 128)
	}
	return h
}

示例#19
文件: create_test.go 项目: jak-atx/vic

func TestParseConatainerNetworkGateways(t *testing.T) {
	var tests = []struct {
		cgs []string
		gws map[string]net.IPNet
		err error
	}{
		{[]string{""}, nil, fmt.Errorf("")},
		{[]string{"foo:"}, nil, fmt.Errorf("")},
		{[]string{":"}, nil, fmt.Errorf("")},
		{[]string{":10.10.10.10/24"}, nil, fmt.Errorf("")},
		{[]string{":foo"}, nil, fmt.Errorf("")},
		{[]string{"foo:10"}, nil, fmt.Errorf("")},
		{[]string{"foo:10.10.10.10/24", "foo:10.10.10.2/24"}, nil, fmt.Errorf("")},
		{
			[]string{"foo:10.10.10.10/24", "bar:10.10.9.1/16"},
			map[string]net.IPNet{
				"foo": net.IPNet{IP: net.ParseIP("10.10.10.10"), Mask: net.CIDRMask(24, 32)},
				"bar": net.IPNet{IP: net.ParseIP("10.10.9.1"), Mask: net.CIDRMask(16, 32)},
			},
			nil,
		},
	}

	for _, te := range tests {
		gws, err := parseContainerNetworkGateways(te.cgs)
		if te.err != nil {
			if err == nil {
				t.Fatalf("parseContainerNetworkGateways(%s) => (%v, nil) want (nil, err)", te.cgs, gws)
			}

			continue
		}

		if err != te.err ||
			gws == nil ||
			len(gws) != len(te.gws) {
			t.Fatalf("parseContainerNetworkGateways(%s) => (%v, %s) want (%v, nil)", te.cgs, gws, err, te.gws)
		}

		for v, g := range gws {
			if g2, ok := te.gws[v]; !ok {
				t.Fatalf("parseContainerNetworkGateways(%s) => (%v, %s) want (%v, nil)", te.cgs, gws, err, te.gws)
			} else if !g2.IP.Equal(g.IP) || bytes.Compare(g2.Mask, g.Mask) != 0 {
				t.Fatalf("parseContainerNetworkGateways(%s) => (%v, %s) want (%v, nil)", te.cgs, gws, err, te.gws)
			}
		}
	}
}

示例#20
文件: db_test.go 项目: postfix/gipam

func BenchmarkMatches(b *testing.B) {
	db := readonlyDB()

	var p *Prefix
	var err error
	for p == nil || err != nil {
		ip := make([]byte, 4)
		for i := range ip {
			ip[i] = byte(rand.Int())
		}
		p = db.Realm("prod").Prefix(&net.IPNet{net.IP(ip), net.CIDRMask(32, 32)})
		p2, err := p.GetLongestMatch()
		if err == nil && reflect.DeepEqual(p, p2) {
			err = errors.New("")
		} else {
			p = p2
		}
	}

	b.ResetTimer()
	for n := 0; n < b.N; n++ {
		if _, err := p.GetMatches(); err != nil {
			b.Fatal(err)
		}
	}
}

示例#21
文件: db_test.go 项目: postfix/gipam

func readonlyDB() *DB {
	numPrefixes := 100
	roDBOnce.Do(func() {
		var prefixes []*net.IPNet
		for _, l := range []int{8, 16, 24, 32} {
			b := l / 8
			for n := 0; n < numPrefixes; n++ {
				ip := make([]byte, 4)
				for i := 0; i < b; i++ {
					ip[i] = byte(rand.Int())
				}
				prefixes = append(prefixes, &net.IPNet{net.IP(ip), net.CIDRMask(l, 32)})
			}
		}

		db, err := New(":memory:")
		if err != nil {
			log.Fatalln(err)
		}

		r := db.Realm("prod")
		if err = r.Create(); err != nil {
			log.Fatalln(err)
		}

		for _, p := range prefixes {
			r.Prefix(p).Create()
		}
		roDB = db
	})
	return roDB
}

示例#22
文件: cidr_set.go 项目: CodeJuan/kubernetes

func (s *cidrSet) getBeginingAndEndIndices(cidr *net.IPNet) (begin, end int, err error) {
	begin, end = 0, s.maxCIDRs
	cidrMask := cidr.Mask
	maskSize, _ := cidrMask.Size()

	if !s.clusterCIDR.Contains(cidr.IP.Mask(s.clusterCIDR.Mask)) && !cidr.Contains(s.clusterCIDR.IP.Mask(cidr.Mask)) {
		return -1, -1, fmt.Errorf("cidr %v is out the range of cluster cidr %v", cidr, s.clusterCIDR)
	}

	if s.clusterMaskSize < maskSize {
		subNetMask := net.CIDRMask(s.subNetMaskSize, 32)
		begin, err = s.getIndexForCIDR(&net.IPNet{
			IP:   cidr.IP.To4().Mask(subNetMask),
			Mask: subNetMask,
		})
		if err != nil {
			return -1, -1, err
		}

		ip := make([]byte, 4)
		ipInt := binary.BigEndian.Uint32(cidr.IP) | (^binary.BigEndian.Uint32(cidr.Mask))
		binary.BigEndian.PutUint32(ip, ipInt)
		end, err = s.getIndexForCIDR(&net.IPNet{
			IP:   net.IP(ip).To4().Mask(subNetMask),
			Mask: subNetMask,
		})
		if err != nil {
			return -1, -1, err
		}
	}
	return begin, end, nil
}

示例#23
文件: cidr_set.go 项目: CodeJuan/kubernetes

func (s *cidrSet) allocateNext() (*net.IPNet, error) {
	s.Lock()
	defer s.Unlock()

	nextUnused := -1
	for i := 0; i < s.maxCIDRs; i++ {
		candidate := (i + s.nextCandidate) % s.maxCIDRs
		if s.used.Bit(candidate) == 0 {
			nextUnused = candidate
			break
		}
	}
	if nextUnused == -1 {
		return nil, errCIDRRangeNoCIDRsRemaining
	}
	s.nextCandidate = (nextUnused + 1) % s.maxCIDRs

	s.used.SetBit(&s.used, nextUnused, 1)

	j := uint32(nextUnused) << uint32(32-s.subNetMaskSize)
	ipInt := (binary.BigEndian.Uint32(s.clusterIP)) | j
	ip := make([]byte, 4)
	binary.BigEndian.PutUint32(ip, ipInt)

	return &net.IPNet{
		IP:   ip,
		Mask: net.CIDRMask(s.subNetMaskSize, 32),
	}, nil
}

示例#24
文件: values.go 项目: svdberg/syncmysport-runkeeper

func decodeInet(vr *ValueReader) net.IPNet {
	var zero net.IPNet

	if vr.Len() == -1 {
		vr.Fatal(ProtocolError("Cannot decode null into net.IPNet"))
		return zero
	}

	if vr.Type().FormatCode != BinaryFormatCode {
		vr.Fatal(ProtocolError(fmt.Sprintf("Unknown field description format code: %v", vr.Type().FormatCode)))
		return zero
	}

	pgType := vr.Type()
	if vr.Len() != 8 && vr.Len() != 20 {
		vr.Fatal(ProtocolError(fmt.Sprintf("Received an invalid size for a %s: %d", pgType.Name, vr.Len())))
		return zero
	}

	if pgType.DataType != InetOid && pgType.DataType != CidrOid {
		vr.Fatal(ProtocolError(fmt.Sprintf("Cannot decode oid %v into %s", pgType.DataType, pgType.Name)))
		return zero
	}

	vr.ReadByte() // ignore family
	bits := vr.ReadByte()
	vr.ReadByte() // ignore is_cidr
	addressLength := vr.ReadByte()

	var ipnet net.IPNet
	ipnet.IP = vr.ReadBytes(int32(addressLength))
	ipnet.Mask = net.CIDRMask(int(bits), int(addressLength)*8)

	return ipnet
}

示例#25
文件: ec2t_test.go 项目: BillTheBest/libswarm

func (s *LocalServerSuite) TestInstanceInfo(c *C) {
	list, err := s.ec2.RunInstances(&ec2.RunInstances{
		ImageId:      imageId,
		InstanceType: "t1.micro",
	})
	c.Assert(err, IsNil)

	inst := list.Instances[0]
	c.Assert(inst, NotNil)

	id := inst.InstanceId
	defer s.ec2.TerminateInstances([]string{id})

	masked := func(addr string) string {
		return net.ParseIP(addr).Mask(net.CIDRMask(24, 32)).String()
	}
	c.Check(masked(inst.IPAddress), Equals, "8.0.0.0")
	c.Check(masked(inst.PrivateIPAddress), Equals, "127.0.0.0")
	// DNSName is empty initially, to check it we need to refresh.
	c.Check(inst.DNSName, Equals, "")
	c.Check(inst.PrivateDNSName, Equals, id+".internal.invalid")

	// Get the instance again to verify DNSName.
	resp, err := s.ec2.Instances([]string{id}, nil)
	c.Assert(err, IsNil)
	c.Assert(resp.Reservations, HasLen, 1)
	c.Assert(resp.Reservations[0].Instances, HasLen, 1)
	c.Check(resp.Reservations[0].Instances[0].DNSName, Equals, id+".testing.invalid")
}

示例#26
文件: compare_test.go 项目: ably-forks/flynn

func (S) TestUnmarshalRoundtrip(c *C) {
	for i, t := range []encoding.BinaryMarshaler{
		Bool(true),
		Bool(false),
		Integers{Integer{IntegerOpGt, 1}},
		Integers{},
		Strings{"foo", "bar"},
		Strings{},
		(*Regexp)(regexp.MustCompile(`\d`)),
		(*Regexp)(regexp.MustCompile("")),
		CIDRs{
			net.IPNet{IP: net.IPv4(127, 0, 0, 1), Mask: net.IPv4Mask(255, 255, 255, 0)},
			net.IPNet{IP: net.IPv6loopback, Mask: net.CIDRMask(8, 16*8)},
		},
		CIDRs{},
	} {
		c.Log(i)
		info := Commentf("i = %d", i)

		b, err := t.MarshalBinary()
		c.Assert(err, IsNil, info)

		parsed, err := UnmarshalBinary(b)
		c.Assert(err, IsNil, info)
		c.Assert(parsed, DeepEquals, t)
	}
}

示例#27
文件: endpoint_test.go 项目: vmware/vic

func TestEndpointCopy(t *testing.T) {
	c := &Container{id: "foo"}
	s := &Scope{
		gateway: net.ParseIP("10.10.10.1"),
		subnet:  &net.IPNet{IP: net.ParseIP("10.10.10.0"), Mask: net.CIDRMask(24, 32)},
	}
	e := Endpoint{
		container: c,
		scope:     s,
		ip:        net.ParseIP("10.10.10.10"),
		static:    true,
		ports:     make(map[Port]interface{}),
	}

	p, err := ParsePort("80/tcp")
	assert.NoError(t, err, "")
	e.ports[p] = nil

	other := e.copy()

	assert.Equal(t, other.ID(), e.ID())
	assert.Equal(t, other.container, c)
	assert.Equal(t, other.container, e.container)
	assert.Equal(t, other.scope, s)
	assert.Equal(t, other.scope, e.scope)
	assert.True(t, other.ip.Equal(e.ip), "other.ip (%s) != e.ip (%s)", other.ip, e.ip)
	assert.True(t, other.Gateway().Equal(e.Gateway()), "other.Gateway() (%s) != e.Gateway() (%s)", other.Gateway(), e.Gateway())
	assert.True(t, other.Subnet().IP.Equal(e.Subnet().IP), "other.Subnet() (%s) != e.Subnet() (%s)", other.Subnet(), e.Subnet())
	assert.Equal(t, other.Subnet().Mask, e.Subnet().Mask, "other.Subnet() (%s) != e.Subnet() (%s)", other.Subnet(), e.Subnet())
	assert.EqualValues(t, other.ports, e.ports)

	// make sure .ports is a copy
	other.ports["foo"] = nil
	assert.NotContains(t, e.ports, "foo")
}

示例#28
文件: db_test.go 项目: postfix/gipam

// This benchmark is mostly useful for very manual inspection and
// debugging, so it's off by default.
func BenchmarkInsertions(b *testing.B) {
	var prefixes []*net.IPNet
	for _, l := range []int{32, 24, 16, 8} {
		for n := 0; n < 1000; n++ {
			b := l / 8
			ip := make([]byte, 4)
			for i := 0; i < b; i++ {
				ip[i] = byte(rand.Int())
			}
			prefixes = append(prefixes, &net.IPNet{net.IP(ip), net.CIDRMask(l, 32)})
		}
	}

	b.ResetTimer()
	for n := 0; n < b.N; n++ {
		db, err := New(":memory:")
		if err != nil {
			b.Fatal("Cannot create in-memory DB:", err)
		}

		r := db.Realm("prod")
		if err = r.Create(); err != nil {
			b.Fatalf("Creating realm: %s", err)
		}

		for _, p := range prefixes {
			r.Prefix(p).Create()
		}
		db.Close()
	}
}

示例#29
文件: ip.go 项目: mad3310/vrouter

func GetAllSubnet(ipnet *net.IPNet, hostbits int) []net.IPNet {
	ones, bits := ipnet.Mask.Size()
	zeros := bits - ones

	// network bits
	netBits := zeros - hostbits
	if netBits < 0 {
		return []net.IPNet{}
	}

	ip4 := ipnet.IP.To4()

	numberSubnet := 1 << uint(netBits)
	subnet := make([]net.IPNet, 0, numberSubnet)

	for i := uint32(0); i < uint32(numberSubnet); i++ {
		ipbuf := make([]byte, 4)
		number := i << uint(hostbits)
		binary.BigEndian.PutUint32(ipbuf, number)

		ip := (((uint32(ipbuf[0]) | uint32(ip4[0])) << 24) |
			((uint32(ipbuf[1]) | uint32(ip4[1])) << 16) |
			((uint32(ipbuf[2]) | uint32(ip4[2])) << 8) |
			uint32(ipbuf[3]) | uint32(ip4[3]+1))
		binary.BigEndian.PutUint32(ipbuf, ip)

		ipmask := net.CIDRMask(bits-hostbits, bits)

		subipnet := net.IPNet{IP: ipbuf, Mask: ipmask}
		subnet = append(subnet, subipnet)
	}

	return subnet

}

示例#30
文件: ip_test.go 项目: kjplatz/vic

func TestAllZerosAddr(t *testing.T) {
	var tests = []struct {
		subnet *net.IPNet
		addr   net.IP
	}{
		{&net.IPNet{IP: net.ParseIP("192.168.0.0"), Mask: net.CIDRMask(16, 32)}, net.ParseIP("192.168.0.0")},
		{&net.IPNet{IP: net.ParseIP("192.168.100.0"), Mask: net.CIDRMask(24, 32)}, net.ParseIP("192.168.100.0")},
	}

	for _, te := range tests {
		addr := AllZerosAddr(te.subnet)
		if !te.addr.Equal(addr) {
			t.Fatalf("AllZerosAddr(%s) => got %s, want %s", te.subnet, addr, te.addr)
		}
	}
}

展开阅读全文