當前位置: 首頁>>代碼示例>>Golang>>正文


Golang net.IPMask函數代碼示例

本文整理匯總了Golang中net.IPMask函數的典型用法代碼示例。如果您正苦於以下問題:Golang IPMask函數的具體用法?Golang IPMask怎麽用?Golang IPMask使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了IPMask函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: parseMask

func parseMask(ips, nms string) string {
	ip := net.ParseIP(ips)
	nmip := net.ParseIP(nms)
	if ip == nil || nmip == nil {
		return fmt.Sprintf("either %s or %s couldn't be parsed as an IP",
			ips, nms)
	}
	// this is a bit of a hack, because using ParseIP to parse
	// something that's actually a v4 netmask doesn't quite work
	nm := net.IPMask(nmip.To4())
	cidr, bits := nm.Size()
	if ip.To4() != nil && nm != nil {
		if bits != 32 {
			return fmt.Sprintf("%s doesn't look like a valid IPv4 netmask", nms)
		}
	} else {
		// IPv6, hopefully
		nm = net.IPMask(nmip)
		cidr, bits = nm.Size()
		if bits != 128 {
			return fmt.Sprintf("%s doesn't look like a valid IPv6 netmask", nms)
		}
	}
	btm, top := maskRange(ip, nm)
	return fmt.Sprintf("%s/%d is in the range %s-%s and has the netmask %s",
		ip, cidr, btm, top, nmip)
}
開發者ID:pzsz,項目名稱:sp0rkle,代碼行數:27,代碼來源:commands.go

示例2: TestGetHostOnlyNetworkWindows10Bug

// Tests a special case where Virtualbox creates the host only network
// successfully but mis-reports the netmask.
func TestGetHostOnlyNetworkWindows10Bug(t *testing.T) {
	cidr := "192.168.99.0/24"
	ip, ipnet, err := net.ParseCIDR(cidr)
	if err != nil {
		t.Fatalf("Error parsing cidr: %s", err)
	}

	// This is a faulty netmask: a VirtualBox bug causes it to be
	// misreported.
	ipnet.Mask = net.IPMask(net.ParseIP("15.0.0.0").To4())

	expectedHostOnlyNetwork := &hostOnlyNetwork{
		IPv4: *ipnet,
	}

	vboxNets := map[string]*hostOnlyNetwork{
		"HostInterfaceNetworking-vboxnet0": expectedHostOnlyNetwork,
	}

	// The Mask that we are passing in will be the "legitimate" mask, so it
	// must differ from the magic buggy mask.
	n := getHostOnlyNetwork(vboxNets, ip, net.IPMask(net.ParseIP("255.255.255.0").To4()))
	if !reflect.DeepEqual(n, expectedHostOnlyNetwork) {
		t.Fatalf("Expected result of calling getHostOnlyNetwork to be the same as expected but it was not:\nexpected: %+v\nactual: %+v\n", expectedHostOnlyNetwork, n)
	}
}
開發者ID:usmanismail,項目名稱:machine,代碼行數:28,代碼來源:network_test.go

示例3: cd_netmask

func cd_netmask(bot *bot.Sp0rkle, line *base.Line, ips, nms string) {
	ip := net.ParseIP(ips)
	nmip := net.ParseIP(nms)
	if ip == nil || nmip == nil {
		bot.ReplyN(line, "either %s or %s couldn't be parsed as an IP", ips, nms)
		return
	}
	// this is a bit of a hack, because using ParseIP to parse
	// something that's actually a v4 netmask doesn't quite work
	nm := net.IPMask(nmip.To4())
	cidr, bits := nm.Size()
	if ip.To4() != nil && nm != nil {
		if bits != 32 {
			bot.ReplyN(line, "%s doesn't look like a valid IPv4 netmask", nms)
			return
		}
	} else {
		// IPv6, hopefully
		nm = net.IPMask(nmip)
		cidr, bits = nm.Size()
		if bits != 128 {
			bot.ReplyN(line, "%s doesn't look like a valid IPv6 netmask", nms)
			return
		}
	}
	btm, top := cd_netmask_range(ip, nm)
	bot.ReplyN(line, "%s/%d is in the range %s-%s and has the netmask %s",
		ip, cidr, btm, top, nmip)
}
開發者ID:b33f,項目名稱:sp0rkle,代碼行數:29,代碼來源:handlers.go

示例4: ReadIPList

func ReadIPList(f io.Reader) (iplist IPList, err error) {
	reader := bufio.NewReader(f)

QUIT:
	for {
		line, err := reader.ReadString('\n')
		switch err {
		case io.EOF:
			if len(line) == 0 {
				break QUIT
			}
		case nil:
		default:
			logger.Err(err)
			return nil, err
		}
		addrs := strings.Split(strings.Trim(line, "\r\n "), " ")
		ipnet := net.IPNet{
			IP:   net.ParseIP(addrs[0]),
			Mask: net.IPMask(net.ParseIP(addrs[1])),
		}
		iplist = append(iplist, ipnet)
	}

	logger.Infof("blacklist loaded %d record(s).", len(iplist))
	return
}
開發者ID:nicecai,項目名稱:goproxy,代碼行數:27,代碼來源:iplist.go

示例5: getSubnet

func getSubnet(ip, netmask string) (string, error) {
	// Check ip
	if net.ParseIP(ip) == nil {
		return "", fmt.Errorf("invalid IP address %s", ip)
	}

	// Check netmask
	maskIP := net.ParseIP(netmask).To4()
	if maskIP == nil {
		return "", fmt.Errorf("invalid Netmask %s", netmask)
	}

	// Get prefix
	mask := net.IPMask(maskIP)
	prefix, _ := mask.Size()

	// Get network
	sPrefix := strconv.Itoa(prefix)
	_, network, err := net.ParseCIDR(ip + "/" + sPrefix)
	if err != nil {
		return "", err
	}

	return network.IP.String() + "/" + sPrefix, nil
}
開發者ID:mickep76,項目名稱:etcdrest,代碼行數:25,代碼來源:template.go

示例6: teardownKvmNets

// teardownKvmNets teardown every active networking from networking by
// removing tuntap interface and releasing its ip from IPAM plugin
func (n *Networking) teardownKvmNets() {
	for _, an := range n.nets {
		switch an.conf.Type {
		case "ptp":
			// remove tuntap interface
			tuntap.RemovePersistentIface(an.runtime.IfName, tuntap.Tap)
			// remove masquerading if it was prepared
			if an.conf.IPMasq {
				h := sha512.Sum512([]byte(n.podID.String()))
				chain := fmt.Sprintf("CNI-%s-%x", an.conf.Name, h[:8])
				err := ip.TeardownIPMasq(&net.IPNet{
					IP:   an.runtime.IP,
					Mask: net.IPMask(an.runtime.Mask),
				}, chain)
				if err != nil {
					log.Printf("Error on removing masquerading: %q", err)
				}
			}
			// ugly hack again to directly call IPAM plugin to release IP
			an.conf.Type = an.conf.IPAM.Type

			_, err := n.execNetPlugin("DEL", &an, an.runtime.IfName)
			if err != nil {
				log.Printf("Error executing network plugin: %q", err)
			}
		default:
			log.Printf("Unsupported network type: %q", an.conf.Type)
		}
	}
}
開發者ID:vincentvdk,項目名稱:rkt,代碼行數:32,代碼來源:kvm.go

示例7: main

func main() {
	flag.Parse()

	lwipv6.Initialize(0)
	defer lwipv6.Finish()

	intf := lwipv6.CreateInterface(lwipv6.IF_VDE, *socket, 0)
	if intf == nil {
		log.Fatalln("Interface setup failed to:", *socket)
	}

	ip := net.IPv4(192, 168, 123, 2)
	mask := net.IPMask(net.IPv4(255, 255, 255, 0))
	if intf.AddAddress(net.IPNet{ip, mask}) != 0 {
		log.Fatalln("Adding address failed.")
	}

	if intf.IfUp(0) != 0 {
		log.Fatalln("Failed bringing interface up")
	}

	fmt.Println("Interface up successfully! Press any key to exit.")
	var input string
	fmt.Scanln(&input)
	fmt.Println("Exiting.")
}
開發者ID:wrouesnel,項目名稱:cgo.lwipv6,代碼行數:26,代碼來源:connect_vde_switch.go

示例8: resolvePeer

func (d *driver) resolvePeer(nid string, peerIP net.IP) (net.HardwareAddr, net.IPMask, net.IP, error) {
	qPayload := fmt.Sprintf("%s %s", string(nid), peerIP.String())
	resp, err := d.serfInstance.Query("peerlookup", []byte(qPayload), nil)
	if err != nil {
		return nil, nil, nil, fmt.Errorf("resolving peer by querying the cluster failed: %v", err)
	}

	respCh := resp.ResponseCh()
	select {
	case r := <-respCh:
		var macStr, maskStr, vtepStr string
		if _, err := fmt.Sscan(string(r.Payload), &macStr, &maskStr, &vtepStr); err != nil {
			return nil, nil, nil, fmt.Errorf("bad response %q for the resolve query: %v", string(r.Payload), err)
		}

		mac, err := net.ParseMAC(macStr)
		if err != nil {
			return nil, nil, nil, fmt.Errorf("failed to parse mac: %v", err)
		}

		return mac, net.IPMask(net.ParseIP(maskStr).To4()), net.ParseIP(vtepStr), nil

	case <-time.After(time.Second):
		return nil, nil, nil, fmt.Errorf("timed out resolving peer by querying the cluster")
	}
}
開發者ID:previousnext,項目名稱:kube-ingress,代碼行數:26,代碼來源:ov_serf.go

示例9: unmarshalIPMask

func unmarshalIPMask(data []byte) (net.IPMask, error) {
	var bytes []byte
	if err := json.Unmarshal([]byte(data), &bytes); err != nil {
		return nil, err
	}
	return net.IPMask(bytes), nil
}
開發者ID:wcwxyz,項目名稱:libnetwork,代碼行數:7,代碼來源:bridge.go

示例10: ReadIPList

func ReadIPList(filename string) (iplist IPList, err error) {
	var f io.ReadCloser
	f, err = os.Open(filename)
	if err != nil {
		return
	}
	defer f.Close()

	if strings.HasSuffix(filename, ".gz") {
		f, err = gzip.NewReader(f)
		if err != nil {
			return
		}
	}

	err = sutils.ReadLines(f, func(line string) (err error) {
		addrs := strings.Split(strings.Trim(line, "\r\n "), " ")
		ipnet := net.IPNet{IP: net.ParseIP(addrs[0]), Mask: net.IPMask(net.ParseIP(addrs[1]))}
		iplist = append(iplist, ipnet)
		return
	})
	if err != nil {
		return
	}
	return
}
開發者ID:justzx2011,項目名稱:goproxy,代碼行數:26,代碼來源:dail.go

示例11: 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

示例12: maskToPrefixlen

// maskToPrefixlen Converts a subnet mask from dotted decimal to bit length
// If mask is not in canonical form (i.e. ones followed by zeros) then
// returns 0
func maskToPrefixlen(mask string) string {
	if mask == "" {
		mask = "255.255.255.255"
	}
	prefixSize, _ := net.IPMask(net.ParseIP(mask).To4()).Size()
	return strconv.Itoa(prefixSize)
}
開發者ID:sysbot,項目名稱:goeapi,代碼行數:10,代碼來源:acl.go

示例13: setupNetworks

// setupNetworks prepares a []network.InterfaceInfo for the given instance. Any
// disabled network interfaces (as discovered from the lshw output for the node)
// will stay disabled.
func (environ *maasEnviron) setupNetworks(inst instance.Instance) ([]network.InterfaceInfo, error) {
	// Get the instance network interfaces first.
	interfaces, err := environ.getInstanceNetworkInterfaces(inst)
	if err != nil {
		return nil, errors.Annotatef(err, "getInstanceNetworkInterfaces failed")
	}
	logger.Debugf("node %q has network interfaces %v", inst.Id(), interfaces)
	networks, err := environ.getInstanceNetworks(inst)
	if err != nil {
		return nil, errors.Annotatef(err, "getInstanceNetworks failed")
	}
	logger.Debugf("node %q has networks %v", inst.Id(), networks)
	var tempInterfaceInfo []network.InterfaceInfo
	for _, netw := range networks {
		netCIDR := &net.IPNet{
			IP:   net.ParseIP(netw.IP),
			Mask: net.IPMask(net.ParseIP(netw.Mask)),
		}
		macs, err := environ.getNetworkMACs(netw.Name)
		if err != nil {
			return nil, errors.Annotatef(err, "getNetworkMACs failed")
		}
		logger.Debugf("network %q has MACs: %v", netw.Name, macs)
		var defaultGateway network.Address
		if netw.DefaultGateway != "" {
			defaultGateway = network.NewAddress(netw.DefaultGateway)
		}
		for _, mac := range macs {
			if ifinfo, ok := interfaces[mac]; ok {
				tempInterfaceInfo = append(tempInterfaceInfo, network.InterfaceInfo{
					MACAddress:     mac,
					InterfaceName:  ifinfo.InterfaceName,
					DeviceIndex:    ifinfo.DeviceIndex,
					CIDR:           netCIDR.String(),
					VLANTag:        netw.VLANTag,
					ProviderId:     network.Id(netw.Name),
					NetworkName:    netw.Name,
					Disabled:       ifinfo.Disabled,
					GatewayAddress: defaultGateway,
				})
			}
		}
	}
	// Verify we filled-in everything for all networks/interfaces
	// and drop incomplete records.
	var interfaceInfo []network.InterfaceInfo
	for _, info := range tempInterfaceInfo {
		if info.ProviderId == "" || info.NetworkName == "" || info.CIDR == "" {
			logger.Infof("ignoring interface %q: missing subnet info", info.InterfaceName)
			continue
		}
		if info.MACAddress == "" || info.InterfaceName == "" {
			logger.Infof("ignoring subnet %q: missing interface info", info.ProviderId)
			continue
		}
		interfaceInfo = append(interfaceInfo, info)
	}
	logger.Debugf("node %q network information: %#v", inst.Id(), interfaceInfo)
	return interfaceInfo, nil
}
開發者ID:OSBI,項目名稱:juju,代碼行數:63,代碼來源:interfaces.go

示例14: parseMask

func parseMask(ips, nms string) string {
	ip := net.ParseIP(ips)
	nmip := net.ParseIP(nms)
	if ip == nil || nmip == nil {
		return fmt.Sprintf("either %s or %s couldn't be parsed as an IP",
			ips, nms)
	}
	if ip.To4() == nil && nmip.To4() != nil ||
		ip.To4() != nil && nmip.To4() == nil {
		return fmt.Sprintf("can't mix v4 and v6 ip / netmask specifications")
	}
	v4 := ip.To4() != nil
	if v4 {
		// Ensure we're working with 32-bit addrs.
		ip = ip.To4()
		nmip = nmip.To4()
	}
	// this is a bit of a hack, because using ParseIP to parse
	// something that's actually a v4 netmask doesn't quite work
	nm := net.IPMask(nmip)
	cidr, bits := nm.Size()
	if v4 && bits != 32 {
		return fmt.Sprintf("%s doesn't look like a valid IPv4 netmask", nms)
	} else if !v4 && bits != 128 {
		return fmt.Sprintf("%s doesn't look like a valid IPv6 netmask", nms)
	}
	btm, top := maskRange(ip, nm)
	if v4 {
		// Ditto.
		btm = btm.To4()
		top = top.To4()
	}
	return fmt.Sprintf("%s/%d is in the range %s-%s and has the netmask %s",
		ip, cidr, btm, top, nmip)
}
開發者ID:gundalow,項目名稱:sp0rkle,代碼行數:35,代碼來源:commands.go

示例15: GenerateNetworkInterfaceUnits

func GenerateNetworkInterfaceUnits(unitsPath string, netDescriptions []netDescriber) error {

	for i, netDescription := range netDescriptions {
		ifName := fmt.Sprintf(networking.IfNamePattern, i)
		netAddress := net.IPNet{
			IP:   netDescription.GuestIP(),
			Mask: net.IPMask(netDescription.Mask()),
		}

		address := netAddress.String()

		mac, err := generateMacAddress()
		if err != nil {
			return err
		}

		opts := []*unit.UnitOption{
			unit.NewUnitOption("Unit", "Description", fmt.Sprintf("Network configuration for device: %v", ifName)),
			unit.NewUnitOption("Unit", "DefaultDependencies", "false"),
			unit.NewUnitOption("Service", "Type", "oneshot"),
			unit.NewUnitOption("Service", "RemainAfterExit", "true"),
			unit.NewUnitOption("Service", "ExecStartPre", downInterfaceCommand(ifName)),
			unit.NewUnitOption("Service", "ExecStartPre", setMacCommand(ifName, mac.String())),
			unit.NewUnitOption("Service", "ExecStartPre", upInterfaceCommand(ifName)),
			unit.NewUnitOption("Service", "ExecStart", addAddressCommand(address, ifName)),
			unit.NewUnitOption("Install", "RequiredBy", "default.target"),
		}

		for _, route := range netDescription.Routes() {
			gw := route.GW
			if gw == nil {
				gw = netDescription.Gateway()
			}

			opts = append(
				opts,
				unit.NewUnitOption(
					"Service",
					"ExecStartPost",
					addRouteCommand(route.Dst.String(), gw.String()),
				),
			)
		}

		unitName := fmt.Sprintf("interface-%s", ifName) + ".service"
		unitBytes, err := ioutil.ReadAll(unit.Serialize(opts))
		if err != nil {
			return fmt.Errorf("failed to serialize network unit file to bytes %q: %v", unitName, err)
		}

		err = ioutil.WriteFile(filepath.Join(unitsPath, unitName), unitBytes, 0644)
		if err != nil {
			return fmt.Errorf("failed to create network unit file %q: %v", unitName, err)
		}

		log.Printf("network unit created: %q in %q (iface=%q, addr=%q)", unitName, unitsPath, ifName, address)
	}
	return nil
}
開發者ID:matomesc,項目名稱:rkt,代碼行數:59,代碼來源:network.go


注:本文中的net.IPMask函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。