当前位置: 首页>>代码示例>>Golang>>正文


Golang IPNet.String方法代码示例

本文整理汇总了Golang中net.IPNet.String方法的典型用法代码示例。如果您正苦于以下问题:Golang IPNet.String方法的具体用法?Golang IPNet.String怎么用?Golang IPNet.String使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在net.IPNet的用法示例。


在下文中一共展示了IPNet.String方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Setup

func (mgr *filterChain) Setup(instanceChain, bridgeName string, ip net.IP, network *net.IPNet) error {
	commands := []*exec.Cmd{
		// Create filter instance chain
		exec.Command("iptables", "--wait", "-N", instanceChain),
		// Allow intra-subnet traffic (Linux ethernet bridging goes through ip stack)
		exec.Command("iptables", "--wait", "-A", instanceChain, "-s", network.String(), "-d", network.String(), "-j", "ACCEPT"),
		// Otherwise, use the default filter chain
		exec.Command("iptables", "--wait", "-A", instanceChain, "--goto", mgr.cfg.DefaultChain),
		// Bind filter instance chain to filter forward chain
		exec.Command("iptables", "--wait", "-I", mgr.cfg.ForwardChain, "2", "--in-interface", bridgeName, "--source", ip.String(), "--goto", instanceChain),
	}

	for _, cmd := range commands {
		buffer := &bytes.Buffer{}
		cmd.Stderr = buffer
		logger := mgr.logger.Session("setup", lager.Data{"cmd": cmd})
		logger.Debug("starting")
		if err := mgr.runner.Run(cmd); err != nil {
			stderr, _ := ioutil.ReadAll(buffer)
			logger.Error("failed", err, lager.Data{"stderr": string(stderr)})
			return fmt.Errorf("iptables_manager: filter: %s", err)
		}
		logger.Debug("ended")
	}

	return nil
}
开发者ID:digideskio,项目名称:guardian,代码行数:27,代码来源:filter.go

示例2: setAddr4

// sets IP4 addr on link removing any existing ones first
func setAddr4(link *netlink.Vxlan, ipn *net.IPNet) error {
	addrs, err := netlink.AddrList(link, syscall.AF_INET)
	if err != nil {
		return err
	}

	addr := netlink.Addr{ipn, ""}
	existing := false
	for _, old := range addrs {
		if old.IPNet.String() == addr.IPNet.String() {
			existing = true
			continue
		}
		if err = netlink.AddrDel(link, &old); err != nil {
			return fmt.Errorf("failed to delete IPv4 addr %s from %s", old.String(), link.Attrs().Name)
		}
	}

	if !existing {
		if err = netlink.AddrAdd(link, &addr); err != nil {
			return fmt.Errorf("failed to add IP address %s to %s: %s", ipn.String(), link.Attrs().Name, err)
		}
	}

	return nil
}
开发者ID:ably-forks,项目名称:flynn,代码行数:27,代码来源:device.go

示例3: generateCMD

func generateCMD(dst net.IPNet, gw net.IP, is_delete bool) []string {
	var netmask_str string = net.IP(dst.Mask).String()
	var ipaddr_str string = dst.IP.String()
	var gateway_str string = gw.String()
	var network_str string = dst.String()

	switch runtime.GOOS {
	case "darwin":
		if is_delete {
			return []string{"route", "delete", "-net",
				ipaddr_str, gateway_str, netmask_str}
		} else {
			return []string{"route", "add", "-net",
				ipaddr_str, gateway_str, netmask_str}
		}
	case "linux":
		if is_delete {
			return []string{"ip", "route", "del", network_str}
		} else {
			return []string{"ip", "route", "add", network_str, "via", gateway_str}
		}
	default:
		return nil
	}

	return nil
}
开发者ID:blahgeek,项目名称:justvpn,代码行数:27,代码来源:route_table.go

示例4: ensureBridgeAddr

func ensureBridgeAddr(br *netlink.Bridge, ipn *net.IPNet, forceAddress bool) error {
	addrs, err := netlink.AddrList(br, syscall.AF_INET)
	if err != nil && err != syscall.ENOENT {
		return fmt.Errorf("could not get list of IP addresses: %v", err)
	}

	// if there're no addresses on the bridge, it's ok -- we'll add one
	if len(addrs) > 0 {
		ipnStr := ipn.String()
		for _, a := range addrs {
			// string comp is actually easiest for doing IPNet comps
			if a.IPNet.String() == ipnStr {
				return nil
			}

			// If forceAddress is set to true then reconfigure IP address otherwise throw error
			if forceAddress {
				if err = deleteBridgeAddr(br, a.IPNet); err != nil {
					return err
				}
			} else {
				return fmt.Errorf("%q already has an IP address different from %v", br.Name, ipn.String())
			}
		}
	}

	addr := &netlink.Addr{IPNet: ipn, Label: ""}
	if err := netlink.AddrAdd(br, addr); err != nil {
		return fmt.Errorf("could not add IP address to %q: %v", br.Name, err)
	}
	return nil
}
开发者ID:tomdee,项目名称:cni,代码行数:32,代码来源:bridge.go

示例5: insertBitMask

func (a *Allocator) insertBitMask(key SubnetKey, pool *net.IPNet) error {
	log.Debugf("Inserting bitmask (%s, %s)", key.String(), pool.String())

	store := a.getStore(key.AddressSpace)
	if store == nil {
		return fmt.Errorf("could not find store for address space %s while inserting bit mask", key.AddressSpace)
	}

	ipVer := getAddressVersion(pool.IP)
	ones, bits := pool.Mask.Size()
	numAddresses := uint32(1 << uint(bits-ones))

	if ipVer == v4 {
		// Do not let broadcast address be reserved
		numAddresses--
	}

	// Generate the new address masks. AddressMask content may come from datastore
	h, err := bitseq.NewHandle(dsDataKey, store, key.String(), numAddresses)
	if err != nil {
		return err
	}

	if ipVer == v4 {
		// Do not let network identifier address be reserved
		h.Set(0)
	}

	a.Lock()
	a.addresses[key] = h
	a.Unlock()
	return nil
}
开发者ID:dhiltgen,项目名称:libnetwork,代码行数:33,代码来源:allocator.go

示例6: parsePoolRequest

func (a *Allocator) parsePoolRequest(addressSpace, pool, subPool string, v6 bool) (*SubnetKey, *net.IPNet, *AddressRange, error) {
	var (
		nw  *net.IPNet
		ipr *AddressRange
		err error
	)

	if addressSpace == "" {
		return nil, nil, nil, ipamapi.ErrInvalidAddressSpace
	}

	if pool == "" && subPool != "" {
		return nil, nil, nil, ipamapi.ErrInvalidSubPool
	}

	if pool == "" {
		return nil, nil, nil, nil
	}

	if _, nw, err = net.ParseCIDR(pool); err != nil {
		return nil, nil, nil, ipamapi.ErrInvalidPool
	}

	if subPool != "" {
		if ipr, err = getAddressRange(subPool, nw); err != nil {
			return nil, nil, nil, err
		}
	}

	return &SubnetKey{AddressSpace: addressSpace, Subnet: nw.String(), ChildSubnet: subPool}, nw, ipr, nil
}
开发者ID:docker,项目名称:docker,代码行数:31,代码来源:allocator.go

示例7: getNextIp

// return an available ip if one is currently available.  If not,
// return the next available ip for the nextwork
func getNextIp(address *net.IPNet) (*net.IP, error) {
	var (
		ownIP     = ipToInt(&address.IP)
		allocated = allocatedIPs[address.String()]
		first, _  = networkdriver.NetworkRange(address)
		base      = ipToInt(&first)
		size      = int(networkdriver.NetworkSize(address.Mask))
		max       = int32(size - 2) // size -1 for the broadcast address, -1 for the gateway address
		pos       = atomic.LoadInt32(&allocated.last)
	)

	var (
		firstNetIP = address.IP.To4().Mask(address.Mask)
		firstAsInt = ipToInt(&firstNetIP) + 1
	)

	for i := int32(0); i < max; i++ {
		pos = pos%max + 1
		next := int32(base + pos)

		if next == ownIP || next == firstAsInt {
			continue
		}

		if !allocated.Exists(int(pos)) {
			ip := intToIP(next)
			allocated.Push(int(pos))
			atomic.StoreInt32(&allocated.last, pos)
			return ip, nil
		}
	}
	return nil, ErrNoAvailableIPs
}
开发者ID:idvoretskyi,项目名称:coreos-kubernetes,代码行数:35,代码来源:allocator.go

示例8: createCBR0

func createCBR0(wantCIDR *net.IPNet) error {
	// recreate cbr0 with wantCIDR
	if err := exec.Command("brctl", "addbr", "cbr0").Run(); err != nil {
		glog.Error(err)
		return err
	}
	if err := exec.Command("ip", "addr", "add", wantCIDR.String(), "dev", "cbr0").Run(); err != nil {
		glog.Error(err)
		return err
	}
	if err := exec.Command("ip", "link", "set", "dev", "cbr0", "mtu", "1460", "up").Run(); err != nil {
		glog.Error(err)
		return err
	}
	// restart docker
	// For now just log the error. The containerRuntime check will catch docker failures.
	// TODO (dawnchen) figure out what we should do for rkt here.
	if util.UsingSystemdInitSystem() {
		if err := exec.Command("systemctl", "restart", "docker").Run(); err != nil {
			glog.Error(err)
		}
	} else {
		if err := exec.Command("service", "docker", "restart").Run(); err != nil {
			glog.Error(err)
		}
	}
	glog.V(2).Info("Recreated cbr0 and restarted docker")
	return nil
}
开发者ID:XiaoningDing,项目名称:UbernetesPOC,代码行数:29,代码来源:container_bridge.go

示例9: initConfigWrite

// Initialize the repo to be used to announce/write config.
// A seperate repo is initialized to read incoming announcements
func initConfigWrite(networkCidr *net.IPNet, hostIface, gitRepoURL string) {
	var err error
	if !pathExists(EndpointPushSubDir) {
		log.Debugf("[ %s ] dir not found, creating it..", EndpointPushSubDir)
		if err = CreatePaths(EndpointPushSubDir); err != nil {
			log.Fatalf("Could not create the directory [ %s ]: %s", EndpointPushSubDir, err)
		} else {
			log.Warnf("Succesfully created the config path [ %s ]", EndpointPushSubDir)
		}
	}
	// Create the cache subdirectories
	time.Sleep(1 * time.Second)
	localEndpointIP, _ := getIfaceAddrStr(hostIface)
	// Fun Go fact: using a + with sprintf is faster then %s since it uses reflection
	endpointFile := fmt.Sprintf(localEndpointIP + dotjson)
	log.Debugf("The endpoint file name is [ %s ] ", endpointFile)
	log.Debugf("Anouncing this endpoint using the source [ %s ] and advertsing network [ %s ] to datastore file [ %s ]", networkCidr, localEndpointIP, endpointFile)
	endpointConfig := &LocalEndpoint{
		Endpoint: localEndpointIP,
		Network:  networkCidr.String(),
		Meta:     "",
	}
	var configAnnounce []LocalEndpoint
	configAnnounce = append(configAnnounce, *endpointConfig)
	marshallConfig(configAnnounce, configFormat, endpointFile)
	if log.GetLevel().String() == "debug" {
		printPretty(configAnnounce, "json")
	}
	// Parse the repo name
	defer gitPushConfig()
}
开发者ID:nerdalert,项目名称:gitnet-overlay,代码行数:33,代码来源:git_writes.go

示例10: SubnetStartMaster

func (master *OsdnMaster) SubnetStartMaster(clusterNetwork *net.IPNet, hostSubnetLength uint32) error {
	subrange := make([]string, 0)
	subnets, err := master.osClient.HostSubnets().List(kapi.ListOptions{})
	if err != nil {
		log.Errorf("Error in initializing/fetching subnets: %v", err)
		return err
	}
	for _, sub := range subnets.Items {
		subrange = append(subrange, sub.Subnet)
		if err = master.networkInfo.validateNodeIP(sub.HostIP); err != nil {
			// Don't error out; just warn so the error can be corrected with 'oc'
			log.Errorf("Failed to validate HostSubnet %s: %v", hostSubnetToString(&sub), err)
		} else {
			log.Infof("Found existing HostSubnet %s", hostSubnetToString(&sub))
		}
	}

	master.subnetAllocator, err = netutils.NewSubnetAllocator(clusterNetwork.String(), hostSubnetLength, subrange)
	if err != nil {
		return err
	}

	go utilwait.Forever(master.watchNodes, 0)
	go utilwait.Forever(master.watchSubnets, 0)
	return nil
}
开发者ID:juanluisvaladas,项目名称:origin,代码行数:26,代码来源:subnets.go

示例11: checkAddress

func checkAddress(address *net.IPNet) {
	key := address.String()
	if _, exists := allocatedIPs[key]; !exists {
		allocatedIPs[key] = &iPSet{}
		availableIPS[key] = &iPSet{}
	}
}
开发者ID:ppearcy,项目名称:docker,代码行数:7,代码来源:allocator.go

示例12: generateRandomNetwork

func generateRandomNetwork(address *net.IPNet) string {
	tick := float64(time.Now().UnixNano() / 1000000)

	ones, bits := address.Mask.Size()
	zeros := bits - ones
	uniqIPsAmount := math.Pow(2.0, float64(zeros))

	rawIP := math.Mod(tick, uniqIPsAmount)

	remainder := rawIP

	remainder, octet4 := math.Modf(remainder / 255.0)
	remainder, octet3 := math.Modf(remainder / 255.0)
	remainder, octet2 := math.Modf(remainder / 255.0)

	base := address.IP

	address.IP = net.IPv4(
		byte(remainder)|base[0],
		byte(octet2*255)|base[1],
		byte(octet3*255)|base[2],
		byte(octet4*255)|base[3],
	)

	address.IP.Mask(address.Mask)

	return address.String()
}
开发者ID:seletskiy,项目名称:hastur,代码行数:28,代码来源:network.go

示例13: addRedirectRules

func addRedirectRules(path string, eIP *net.IPNet, ingressPorts []*PortConfig) error {
	var ingressPortsFile string

	if len(ingressPorts) != 0 {
		var err error
		ingressPortsFile, err = writePortsToFile(ingressPorts)
		if err != nil {
			return err
		}
		defer os.Remove(ingressPortsFile)
	}

	cmd := &exec.Cmd{
		Path:   reexec.Self(),
		Args:   append([]string{"redirecter"}, path, eIP.String(), ingressPortsFile),
		Stdout: os.Stdout,
		Stderr: os.Stderr,
	}

	if err := cmd.Run(); err != nil {
		return fmt.Errorf("reexec failed: %v", err)
	}

	return nil
}
开发者ID:SUSE,项目名称:docker.mirror,代码行数:25,代码来源:service_linux.go

示例14: NextAddr

func (this pool) NextAddr(args ...interface{}) string {
	var addr, netmask string
	var ipnet *net.IPNet

	switch len(args) {
	case 2:
		addr = args[0].(string)
		netmask = args[1].(string)
		ipnet = &net.IPNet{
			IP:   net.ParseIP(addr),
			Mask: net.IPMask(net.ParseIP(netmask)),
		}

	case 0:
		for k, _ := range this.cache {
			ipnet = this.cache[k]
			break
		}
	default:
		return ""
	}

	ip, _, _ := net.ParseCIDR(this.NextCidr(ipnet.String()))

	return ip.String()
}
开发者ID:NodePrime,项目名称:open-mininet,代码行数:26,代码来源:pool.go

示例15: setAddress

func setAddress(ifaceAddr *string, address *net.IPNet) error {
	if *ifaceAddr != "" {
		return types.ForbiddenErrorf("endpoint interface IP present (%s). Cannot be modified with (%s).", *ifaceAddr, address)
	}
	*ifaceAddr = address.String()
	return nil
}
开发者ID:YujiOshima,项目名称:libnetwork,代码行数:7,代码来源:driver_test.go


注:本文中的net.IPNet.String方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。