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


Golang IP.To4方法代碼示例

本文整理匯總了Golang中net.IP.To4方法的典型用法代碼示例。如果您正苦於以下問題:Golang IP.To4方法的具體用法?Golang IP.To4怎麽用?Golang IP.To4使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在net.IP的用法示例。


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

示例1: ContainsIpAddress

// ContainsIpAddress performs a binary search on the networkList to
// find a network containing the candidate IP address.
func (list networkList) ContainsIpAddress(addr net.IP) bool {

	// Search criteria
	//
	// The following conditions are satisfied when address_IP is in the network:
	// 1. address_IP ^ network_mask == network_IP ^ network_mask
	// 2. address_IP >= network_IP.
	// We are also assuming that network ranges do not overlap.
	//
	// For an ascending array of networks, the sort.Search returns the smallest
	// index idx for which condition network_IP > address_IP is satisfied, so we
	// are checking whether or not adrress_IP belongs to the network[idx-1].

	// Edge conditions check
	//
	// idx == 0 means that address_IP is  lesser than the first (smallest) network_IP
	// thus never satisfies search condition 2.
	// idx == array_length means that address_IP is larger than the last (largest)
	// network_IP so we need to check the last element for condition 1.

	addrValue := binary.BigEndian.Uint32(addr.To4())
	index := sort.Search(len(list), func(i int) bool {
		networkValue := binary.BigEndian.Uint32(list[i].IP)
		return networkValue > addrValue
	})
	return index > 0 && list[index-1].IP.Equal(addr.Mask(list[index-1].Mask))
}
開發者ID:yangguangyu,項目名稱:psiphon-tunnel-core,代碼行數:29,代碼來源:splitTunnel.go

示例2: getDNSRecordTypeByIP

// getDNSRecordTypeByIP returns the DNS record type for the given IP.
// It will return "A" for an IPv4 address and "AAAA" for an IPv6 address.
func getDNSRecordTypeByIP(ip net.IP) string {
	if ip.To4() == nil {
		return "AAAA"
	}

	return "A"
}
開發者ID:andreaskoch,項目名稱:dee-cli,代碼行數:9,代碼來源:util.go

示例3: GetPrivateIP

// GetPrivateIP returns the first private IP address found in a list of
// addresses.
func GetPrivateIP(addresses []net.Addr) (net.IP, error) {
	var candidates []net.IP

	// Find private IPv4 address
	for _, rawAddr := range addresses {
		var ip net.IP
		switch addr := rawAddr.(type) {
		case *net.IPAddr:
			ip = addr.IP
		case *net.IPNet:
			ip = addr.IP
		default:
			continue
		}

		if ip.To4() == nil {
			continue
		}
		if !IsPrivateIP(ip.String()) {
			continue
		}
		candidates = append(candidates, ip)
	}
	numIps := len(candidates)
	switch numIps {
	case 0:
		return nil, fmt.Errorf("No private IP address found")
	case 1:
		return candidates[0], nil
	default:
		return nil, fmt.Errorf("Multiple private IPs found. Please configure one.")
	}
}
開發者ID:CadeLaRen,項目名稱:docker-3,代碼行數:35,代碼來源:util.go

示例4: GetPrivateIP

// GetPrivateIP is used to return the first private IP address
// associated with an interface on the machine
func GetPrivateIP() (net.IP, error) {
	addresses, err := net.InterfaceAddrs()
	if err != nil {
		return nil, fmt.Errorf("Failed to get interface addresses: %v", err)
	}

	// Find private IPv4 address
	for _, rawAddr := range addresses {
		var ip net.IP
		switch addr := rawAddr.(type) {
		case *net.IPAddr:
			ip = addr.IP
		case *net.IPNet:
			ip = addr.IP
		default:
			continue
		}

		if ip.To4() == nil {
			continue
		}
		if !isPrivateIP(ip.String()) {
			continue
		}

		return ip, nil
	}

	return nil, fmt.Errorf("No private IP address found")
}
開發者ID:peoplemerge,項目名稱:consul,代碼行數:32,代碼來源:util.go

示例5: ipAddress

// Gets the ipv4 addr for a network interface
func (f *NetworkFingerprint) ipAddress(intf *net.Interface) (string, error) {
	var addrs []net.Addr
	var err error

	if addrs, err = f.interfaceDetector.Addrs(intf); err != nil {
		return "", err
	}

	if len(addrs) == 0 {
		return "", errors.New(fmt.Sprintf("Interface %s has no IP address", intf.Name))
	}
	for _, addr := range addrs {
		var ip net.IP
		switch v := (addr).(type) {
		case *net.IPNet:
			ip = v.IP
		case *net.IPAddr:
			ip = v.IP
		}
		if ip.To4() != nil {
			return ip.String(), nil
		}
	}

	return "", fmt.Errorf("Couldn't parse IP address for interface %s", intf.Name)

}
開發者ID:PagerDuty,項目名稱:nomad,代碼行數:28,代碼來源:network.go

示例6: bigForIP

// bigForIP creates a big.Int based on the provided net.IP
func bigForIP(ip net.IP) *big.Int {
	b := ip.To4()
	if b == nil {
		b = ip.To16()
	}
	return big.NewInt(0).SetBytes(b)
}
開發者ID:qinguoan,項目名稱:vulcan,代碼行數:8,代碼來源:allocator.go

示例7: getIP

func getIP() string {
	ifaces, err := net.Interfaces()
	if err != nil {
		logger.WithField("_block", "getIP").Error(err)
		return "127.0.0.1"
	}
	for _, i := range ifaces {
		addrs, err := i.Addrs()
		if err != nil {
			logger.WithField("_block", "getIP").Error(err)
			return "127.0.0.1"
		}
		for _, addr := range addrs {
			var ip net.IP
			switch v := addr.(type) {
			case *net.IPAddr:
				ip = v.IP
			case *net.IPNet:
				ip = v.IP
			}
			if ip == nil || ip.IsLoopback() {
				continue
			}
			ip = ip.To4()
			if ip == nil {
				continue // not an ipv4 address
			}
			return ip.String()
		}
	}
	return "127.0.0.1"
}
開發者ID:jeffweiss,項目名稱:snap,代碼行數:32,代碼來源:flags.go

示例8: checkAddressFamily

func checkAddressFamily(ip net.IP) (*api.AddressFamily, error) {
	var rf *api.AddressFamily
	var e error
	switch subOpts.AddressFamily {
	case "ipv4", "v4", "4":
		rf = api.AF_IPV4_UC
	case "ipv6", "v6", "6":
		rf = api.AF_IPV6_UC
	case "vpnv4", "vpn-ipv4":
		rf = api.AF_IPV4_VPN
	case "vpnv6", "vpn-ipv6":
		rf = api.AF_IPV6_VPN
	case "evpn":
		rf = api.AF_EVPN
	case "encap":
		rf = api.AF_ENCAP
	case "rtc":
		rf = api.AF_RTC
	case "":
		if len(ip) == 0 || ip.To4() != nil {
			rf = api.AF_IPV4_UC
		} else {
			rf = api.AF_IPV6_UC
		}
	default:
		e = fmt.Errorf("unsupported address family: %s", subOpts.AddressFamily)
	}
	return rf, e
}
開發者ID:ttaanngg,項目名稱:gobgp,代碼行數:29,代碼來源:common.go

示例9: Release

// Release allows releasing the address from the specified address space
func (a *Allocator) Release(addrSpace AddressSpace, address net.IP) {
	if address == nil {
		return
	}
	ver := getAddressVersion(address)
	if ver == v4 {
		address = address.To4()
	}
	for _, subKey := range a.getSubnetList(addrSpace, ver) {
		a.Lock()
		space := a.addresses[subKey]
		a.Unlock()
		sub := subKey.canonicalChildSubnet()
		if sub.Contains(address) {
			// Retrieve correspondent ordinal in the subnet
			ordinal := ipToInt(getHostPortionIP(address, sub))
			// Release it
			for {
				var err error
				if err = space.PushReservation(ordinal/8, ordinal%8, true); err == nil {
					break
				}
				if _, ok := err.(types.RetryError); ok {
					// bitmask must have changed, retry delete
					continue
				}
				log.Warnf("Failed to release address %s because of internal error: %s", address.String(), err.Error())
				return
			}
			return
		}

	}
}
開發者ID:hariharan16s,項目名稱:libnetwork,代碼行數:35,代碼來源:allocator.go

示例10: removeRoutes

// removeRoutes deletes the routing table entries for a VIP, from the specified
// table.
func removeRoutes(table string, vip net.IP) error {
	af := seesaw.IPv6
	if vip.To4() != nil {
		af = seesaw.IPv4
	}
	return ipRunAF(af, "route flush table %s %s", table, vip)
}
開發者ID:Cepave,項目名稱:lvs-metrics,代碼行數:9,代碼來源:ip.go

示例11: macAddress

func macAddress() (string, error) {
	ifaces, err := net.Interfaces()

	if err != nil {
		return "", err
	}

	for _, iface := range ifaces {
		if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
			// interface down or loopback interface
			continue
		}
		addrs, err := iface.Addrs()
		if err != nil {
			return "", err
		}
		for _, addr := range addrs {
			var ip net.IP
			switch v := addr.(type) {
			case *net.IPNet:
				ip = v.IP
			case *net.IPAddr:
				ip = v.IP
			}
			if ip == nil || ip.IsLoopback() || ip.To4() == nil {
				continue
			}
			return iface.HardwareAddr.String(), nil
		}
	}
	return "", errors.New("not connected to the network")
}
開發者ID:startover,項目名稱:gohai,代碼行數:32,代碼來源:network_common.go

示例12: main

func main() {
	defer util.Run()()
	router, err := routing.New()
	if err != nil {
		log.Fatal("routing error:", err)
	}
	for _, arg := range flag.Args() {
		var ip net.IP
		if ip = net.ParseIP(arg); ip == nil {
			log.Printf("non-ip target: %q", arg)
			continue
		} else if ip = ip.To4(); ip == nil {
			log.Printf("non-ipv4 target: %q", arg)
			continue
		}
		// Note:  newScanner creates and closes a pcap Handle once for
		// every scan target.  We could do much better, were this not an
		// example ;)
		s, err := newScanner(ip, router)
		if err != nil {
			log.Printf("unable to create scanner for %v: %v", ip, err)
			continue
		}
		if err := s.scan(); err != nil {
			log.Printf("unable to scan %v: %v", ip, err)
		}
		s.close()
	}
}
開發者ID:CNDonny,項目名稱:scope,代碼行數:29,代碼來源:main.go

示例13: isMulticastAvailable

// isMulticastAvailable returns true if ifi is a multicast access
// enabled network interface.  It also returns a unicast IPv4 address
// that can be used for listening on ifi.
func isMulticastAvailable(ifi *net.Interface) (net.IP, bool) {
	if ifi.Flags&net.FlagUp == 0 || ifi.Flags&net.FlagMulticast == 0 {
		return nil, false
	}
	ifat, err := ifi.Addrs()
	if err != nil {
		return nil, false
	}
	if len(ifat) == 0 {
		return nil, false
	}
	var ip net.IP
	for _, ifa := range ifat {
		switch v := ifa.(type) {
		case *net.IPAddr:
			ip = v.IP
		case *net.IPNet:
			ip = v.IP
		default:
			continue
		}
		if ip.To4() == nil {
			ip = nil
			continue
		}
		break
	}
	return ip, true
}
開發者ID:98pm,項目名稱:docker,代碼行數:32,代碼來源:mocktransponder_test.go

示例14: GetLocalIP

func GetLocalIP() (ip net.IP, err error) {
	ifaces, err := net.Interfaces()
	if err != nil {
		return nil, err
	}
	// handle err
	for _, i := range ifaces {
		addrs, err := i.Addrs()
		if err != nil {
			return nil, err
		}
		for _, addr := range addrs {
			var ip net.IP
			switch v := addr.(type) {
			case *net.IPNet:
				ip = v.IP

			case *net.IPAddr:
				ip = v.IP
			}
			log.Println(ip.String())
			if !ip.IsLoopback() && ip.String() != "0.0.0.0" && ip.To4() != nil {
				return ip, nil
			}
		}
	}
	return nil, err
}
開發者ID:rhino1998,項目名稱:cluster,代碼行數:28,代碼來源:util.go

示例15: AddDefaultGw

// Add a new default gateway. Identical to:
// ip route add default via $ip
func AddDefaultGw(ip net.IP) error {
	s, err := getNetlinkSocket()
	if err != nil {
		return err
	}
	defer s.Close()

	family := getIpFamily(ip)

	wb := newNetlinkRequest(syscall.RTM_NEWROUTE, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)

	msg := newRtMsg(family)
	wb.AddData(msg)

	var ipData []byte
	if family == syscall.AF_INET {
		ipData = ip.To4()
	} else {
		ipData = ip.To16()
	}

	gateway := newRtAttr(syscall.RTA_GATEWAY, ipData)

	wb.AddData(gateway)

	if err := s.Send(wb); err != nil {
		return err
	}

	return s.HandleAck(wb.Seq)
}
開發者ID:RubanDeventhiran,項目名稱:coreos-cloudinit,代碼行數:33,代碼來源:netlink_linux.go


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