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


Golang net.LookupIP函数代码示例

本文整理汇总了Golang中net.LookupIP函数的典型用法代码示例。如果您正苦于以下问题:Golang LookupIP函数的具体用法?Golang LookupIP怎么用?Golang LookupIP使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: shouldReconnect

func shouldReconnect(hostname string) bool {
	target := strings.Split(hostname, ":")[0] //Remove port from string
	ips, err := net.LookupIP(target)
	if err != nil {
		log.Println("Unable to perform DNS lookup for domain with err:", err)
		return false
	}

	newIps, err := net.LookupIP(target)
	if err != nil {
		log.Println(err)
	}

	for i := 0; i < len(newIps); i++ {
		foundIt := false
		for k := 0; k < len(ips); k++ {
			if ips[k].Equal(newIps[i]) {
				foundIt = true
				break
			}
		}

		if foundIt == false {
			return true
		}
	}

	return false
}
开发者ID:trustpilot,项目名称:dockerlogger,代码行数:29,代码来源:supervisor.go

示例2: findMinionForHost

/* YARN returns hostnames, but minions maybe using IPs.
TODO: This is an expensive mechanism to find the right minion corresponding to the YARN node.
Find a better mechanism if possible (at a minimum - caching could be added in some form)
*/
func findMinionForHost(host string, minionLister MinionLister) (string, error) {
	hostIPs, err := net.LookupIP(host)

	if err != nil {
		return "<invalid_host>", errors.New("unable to lookup IPs for YARN host: " + host)
	}

	for _, hostIP := range hostIPs {
		minions, err := minionLister.List()
		if err != nil {
			return "<invalid_host>", errors.New("update to list minions")
		}

		for _, minion := range minions.Items {
			minionStr := minion.Name
			minionIPs, err := net.LookupIP(minionStr)

			if err != nil {
				return "<invalid_host>", errors.New("unable to lookup IPs for minion: " + minionStr)
			}

			for _, minionIP := range minionIPs {
				if hostIP.Equal(minionIP) {
					log.Printf("YARN node %s maps to minion: %s", host, minionStr)
					return minionStr, nil
				}
			}
		}
	}

	return "<invalid_host>", errors.New("unable to find minion for YARN host: " + host)
}
开发者ID:hortonworks,项目名称:kubernetes-yarn,代码行数:36,代码来源:yarn.go

示例3: Register

// Register a service by given arguments. This call will take the system's hostname
// and lookup IP by that hostname.
func Register(instance, service, domain string, port int, text []string, iface *net.Interface) (*Server, error) {
	entry := NewServiceEntry(instance, service, domain)
	entry.Port = port
	entry.Text = text

	if entry.Instance == "" {
		return nil, fmt.Errorf("Missing service instance name")
	}
	if entry.Service == "" {
		return nil, fmt.Errorf("Missing service name")
	}
	if entry.Domain == "" {
		entry.Domain = "local"
	}
	if entry.Port == 0 {
		return nil, fmt.Errorf("Missing port")
	}

	var err error
	if entry.HostName == "" {
		entry.HostName, err = os.Hostname()
		if err != nil {
			return nil, fmt.Errorf("Could not determine host")
		}
	}
	entry.HostName = fmt.Sprintf("%s.", trimDot(entry.HostName))

	addrs, err := net.LookupIP(entry.HostName)
	if err != nil {
		// Try appending the host domain suffix and lookup again
		// (required for Linux-based hosts)
		tmpHostName := fmt.Sprintf("%s%s.", entry.HostName, entry.Domain)
		addrs, err = net.LookupIP(tmpHostName)
		if err != nil {
			return nil, fmt.Errorf("Could not determine host IP addresses for %s", entry.HostName)
		}
	}
	for i := 0; i < len(addrs); i++ {
		if ipv4 := addrs[i].To4(); ipv4 != nil {
			entry.AddrIPv4 = addrs[i]
		} else if ipv6 := addrs[i].To16(); ipv6 != nil {
			entry.AddrIPv6 = addrs[i]
		}
	}

	s, err := newServer(iface)
	if err != nil {
		return nil, err
	}

	s.service = entry
	go s.mainloop()
	go s.probe()

	return s, nil
}
开发者ID:edc1591,项目名称:gohome,代码行数:58,代码来源:server.go

示例4: normalizeAdvertise

// normalizeAdvertise returns a normalized advertise address.
//
// If addr is set, it is used and the default port is appended if no port is
// set.
//
// If addr is not set and bind is a valid address, the returned string is the
// bind+port.
//
// If addr is not set and bind is not a valid advertise address, the hostname
// is resolved and returned with the port.
//
// Loopback is only considered a valid advertise address in dev mode.
func normalizeAdvertise(addr string, bind string, defport int, dev bool) (string, error) {
	if addr != "" {
		// Default to using manually configured address
		_, _, err := net.SplitHostPort(addr)
		if err != nil {
			if !isMissingPort(err) {
				return "", fmt.Errorf("Error parsing advertise address %q: %v", addr, err)
			}

			// missing port, append the default
			return net.JoinHostPort(addr, strconv.Itoa(defport)), nil
		}
		return addr, nil
	}

	// Fallback to bind address first, and then try resolving the local hostname
	ips, err := net.LookupIP(bind)
	if err != nil {
		return "", fmt.Errorf("Error resolving bind address %q: %v", bind, err)
	}

	// Return the first unicast address
	for _, ip := range ips {
		if ip.IsLinkLocalUnicast() || ip.IsGlobalUnicast() {
			return net.JoinHostPort(ip.String(), strconv.Itoa(defport)), nil
		}
		if ip.IsLoopback() && dev {
			// loopback is fine for dev mode
			return net.JoinHostPort(ip.String(), strconv.Itoa(defport)), nil
		}
	}

	// As a last resort resolve the hostname and use it if it's not
	// localhost (as localhost is never a sensible default)
	host, err := os.Hostname()
	if err != nil {
		return "", fmt.Errorf("Unable to get hostname to set advertise address: %v", err)
	}

	ips, err = net.LookupIP(host)
	if err != nil {
		return "", fmt.Errorf("Error resolving hostname %q for advertise address: %v", host, err)
	}

	// Return the first unicast address
	for _, ip := range ips {
		if ip.IsLinkLocalUnicast() || ip.IsGlobalUnicast() {
			return net.JoinHostPort(ip.String(), strconv.Itoa(defport)), nil
		}
		if ip.IsLoopback() && dev {
			// loopback is fine for dev mode
			return net.JoinHostPort(ip.String(), strconv.Itoa(defport)), nil
		}
	}
	return "", fmt.Errorf("No valid advertise addresses, please set `advertise` manually")
}
开发者ID:zanella,项目名称:nomad,代码行数:68,代码来源:config.go

示例5: Init

// Init should be called to setup the internal state
func (m *MDNSService) Init() error {
	// Setup default domain
	if m.Domain == "" {
		m.Domain = "local"
	}

	// Sanity check inputs
	if m.Instance == "" {
		return fmt.Errorf("Missing service instance name")
	}
	if m.Service == "" {
		return fmt.Errorf("Missing service name")
	}
	if m.Port == 0 {
		return fmt.Errorf("Missing service port")
	}

	// Get host information
	hostName, err := os.Hostname()
	if err == nil {
		m.HostName = fmt.Sprintf("%s.", hostName)

		addrs, err := net.LookupIP(m.HostName)
		if err != nil {
			// Try appending the host domain suffix and lookup again
			// (required for Linux-based hosts)
			tmpHostName := fmt.Sprintf("%s%s.", m.HostName, m.Domain)

			addrs, err = net.LookupIP(tmpHostName)

			if err != nil {
				return fmt.Errorf("Could not determine host IP addresses for %s", m.HostName)
			}
		}

		for i := 0; i < len(addrs); i++ {
			if ipv4 := addrs[i].To4(); ipv4 != nil {
				m.ipv4Addr = addrs[i]
			} else if ipv6 := addrs[i].To16(); ipv6 != nil {
				m.ipv6Addr = addrs[i]
			}
		}
	} else {
		return fmt.Errorf("Could not determine host")
	}

	// Create the full addresses
	m.serviceAddr = fmt.Sprintf("%s.%s.",
		trimDot(m.Service), trimDot(m.Domain))
	m.instanceAddr = fmt.Sprintf("%s.%s",
		trimDot(m.Instance), m.serviceAddr)
	return nil
}
开发者ID:richtr,项目名称:mdns,代码行数:54,代码来源:zone.go

示例6: main

func main() {
	kListenStr := flag.String("l", "localhost:8000", "the address:port the kademlia instance will operate over")
	htmlDirPath := flag.String("d", "/home/jch570/public_html/", "the path to the directory where html files are served. file is written out to this dir")
	htmlFileName := flag.String("f", "dms.html", "filename where drymartini info will be written out")
	flag.Parse()
	listenStr := *kListenStr

	log.Printf("dmTracker listening on:%s\n", listenStr)

	var junk = "junk"
	kademInst, _ := kademlia.NewKademlia(listenStr, &junk)

	log.Printf("dmTracker checking querying initial core: %+v\n", coreKadems)
	// commenting out, for testing just going to use localhost:8000-8004
	for _, apPair := range coreKadems {
		ipList, err := net.LookupIP(apPair.addr)
		if err != nil {
			log.Printf("error looking up addr:%s. Err:%s\n", apPair.addr, err)
		}
		kademlia.MakePingCall(kademInst, ipList[0], apPair.port)
	}

	//test should trash soon
	for i := 0; i < 5; i++ {
		ipList, err := net.LookupIP("localhost")
		if err != nil {
			log.Printf("error looking up addr\n")
		}
		kademlia.MakePingCall(kademInst, ipList[0], uint16(8000+i))
	}
	//end junk

	kademlia.DoJoin(kademInst)
	var contacts []kademlia.Contact
	contacts = kademlia.BucketsAsArray(kademInst)

	log.Printf("local buckets as array:\n %+v\n", contacts)

	f, err := os.Create(*htmlDirPath + *htmlFileName)
	if err != nil { //"./testoutput"); if(err!=nil){//
		log.Printf("error creating file:%s\n", err)
		os.Exit(1)
	}
	f.Write([]byte("DryMartinis found:\n"))
	var c kademlia.Contact
	for _, c = range contacts {
		f.Write([]byte(c.AsString() + "\n"))
	}
	f.Write([]byte("last updated: " + time.Now().String()))
	f.Close()

}
开发者ID:johhud1,项目名称:KademliaMixNetwork,代码行数:52,代码来源:dmTracker.go

示例7: resolveTCPAddrs

func resolveTCPAddrs(addr string, dualStack bool) ([]net.TCPAddr, error) {
	host, portS, err := net.SplitHostPort(addr)
	if err != nil {
		return nil, err
	}
	port, err := strconv.Atoi(portS)
	if err != nil {
		return nil, err
	}

	ips, err := net.LookupIP(host)
	if err != nil {
		return nil, err
	}

	n := len(ips)
	addrs := make([]net.TCPAddr, 0, n)
	for i := 0; i < n; i++ {
		ip := ips[i]
		if !dualStack && ip.To4() == nil {
			continue
		}
		addrs = append(addrs, net.TCPAddr{
			IP:   ip,
			Port: port,
		})
	}
	if len(addrs) == 0 {
		return nil, errNoDNSEntries
	}
	return addrs, nil
}
开发者ID:valyala,项目名称:fasthttp,代码行数:32,代码来源:tcpdialer.go

示例8: GetColocatedHost

// GetColocatedHost find the server addr for localhost and return the same.
func GetColocatedHost(cluster string) (string, error) {
	// get vbmap from bucket connection.
	bucket, err := ConnectBucket(cluster, "default", "default")
	if err != nil {
		return "", err
	}
	defer bucket.Close()

	hostports := bucket.NodeAddresses()
	serversM := make(map[string]string)
	servers := make([]string, 0)
	for _, hostport := range hostports {
		host, _, err := net.SplitHostPort(hostport)
		if err != nil {
			return "", err
		}
		serversM[host] = hostport
		servers = append(servers, host)
	}

	for _, server := range servers {
		addrs, err := net.LookupIP(server)
		if err != nil {
			return "", err
		}
		for _, addr := range addrs {
			if IsIPLocal(addr.String()) {
				return serversM[server], nil
			}
		}
	}
	return "", errors.New("unknown host")
}
开发者ID:jchris,项目名称:indexing,代码行数:34,代码来源:util.go

示例9: allocateDaemonPort

// allocateDaemonPort ensures that there are no containers
// that try to use any port allocated for the docker server.
func allocateDaemonPort(addr string) error {
	host, port, err := net.SplitHostPort(addr)
	if err != nil {
		return err
	}

	intPort, err := strconv.Atoi(port)
	if err != nil {
		return err
	}

	var hostIPs []net.IP
	if parsedIP := net.ParseIP(host); parsedIP != nil {
		hostIPs = append(hostIPs, parsedIP)
	} else if hostIPs, err = net.LookupIP(host); err != nil {
		return fmt.Errorf("failed to lookup %s address in host specification", host)
	}

	pa := portallocator.Get()
	for _, hostIP := range hostIPs {
		if _, err := pa.RequestPort(hostIP, "tcp", intPort); err != nil {
			return fmt.Errorf("failed to allocate daemon listening port %d (err: %v)", intPort, err)
		}
	}
	return nil
}
开发者ID:fntlnz,项目名称:docker,代码行数:28,代码来源:daemon_unix.go

示例10: Dial

func (d *Dailer) Dial(network, address string) (net.Conn, error) {
	switch network {
	case "tcp", "tcp4", "tcp6":
		if d.DNSCache != nil {
			if addr, ok := d.DNSCache.Get(address); ok {
				address = addr.(string)
			} else {
				if host, port, err := net.SplitHostPort(address); err == nil {
					if ips, err := net.LookupIP(host); err == nil && len(ips) > 0 {
						ip := ips[0].String()
						if _, ok := d.LoopbackAddrs[ip]; ok {
							return nil, net.InvalidAddrError(fmt.Sprintf("Invaid DNS Record: %s(%s)", host, ip))
						}
						addr := net.JoinHostPort(ip, port)
						d.DNSCache.Set(address, addr, time.Now().Add(d.DNSCacheExpires))
						glog.V(3).Infof("direct Dial cache dns %#v=%#v", address, addr)
						address = addr
					}
				}
			}
		}
	default:
		break
	}
	return d.Dialer.Dial(network, address)
}
开发者ID:snowink,项目名称:goproxy,代码行数:26,代码来源:dialer.go

示例11: lookupIPs

func (c *Client) lookupIPs(host string) (ips []net.IP, err error) {
	m := new(dns.Msg)
	for _, resolver := range c.Resolvers {
		m.SetQuestion(dns.Fqdn(host), dns.TypeA)
		if in, err := dns.Exchange(m, resolver); err == nil {
			for _, rr := range in.Answer {
				if a, ok := rr.(*dns.A); ok {
					ips = append(ips, a.A)
				}
			}
		} else {
			log.Debug(err)
		}

		m.SetQuestion(dns.Fqdn(host), dns.TypeAAAA)
		if in, err := dns.Exchange(m, resolver); err == nil {
			for _, rr := range in.Answer {
				if aaaa, ok := rr.(*dns.AAAA); ok {
					ips = append(ips, aaaa.AAAA)
				}
			}
		} else {
			log.Debug(err)
		}
	}
	if len(ips) != 0 {
		return ips, nil
	}

	return net.LookupIP(host)
}
开发者ID:vsayer,项目名称:gokeyless,代码行数:31,代码来源:remote.go

示例12: iplookup

func (f *apiHandler) iplookup(writer writerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		host := httpmux.Params(r).ByName("host")
		if len(host) > 0 && host[0] == '/' {
			host = host[1:]
		}
		if host == "" {
			host, _, _ = net.SplitHostPort(r.RemoteAddr)
			if host == "" {
				host = r.RemoteAddr
			}
		}
		ips, err := net.LookupIP(host)
		if err != nil || len(ips) == 0 {
			http.NotFound(w, r)
			return
		}
		ip, q := ips[rand.Intn(len(ips))], &geoipQuery{}
		err = f.db.Lookup(ip, &q.DefaultQuery)
		if err != nil {
			http.Error(w, "Try again later.", http.StatusServiceUnavailable)
			return
		}
		w.Header().Set("X-Database-Date", f.db.Date().Format(http.TimeFormat))
		resp := q.Record(ip, r.Header.Get("Accept-Language"))
		writer(w, r, resp)
	}
}
开发者ID:mathieu-aubin,项目名称:freegeoip,代码行数:28,代码来源:api.go

示例13: AuthenticationAPI

func AuthenticationAPI(w rest.ResponseWriter, req *rest.Request) {
	fmt.Println(":: AuthenticationAPI ::")
	ip, _ := net.LookupIP(req.PathParam("host"))
	// rest.Error(w, err.Error(), http.StatusInternalServerError)
	w.WriteJson(&ip)
	w.WriteJson(map[string]interface{}{"Body": ip})
}
开发者ID:AnuchitPrasertsang,项目名称:golang-middleware-test,代码行数:7,代码来源:main.go

示例14: Lookup

// Lookup an address' ip, circumventing the cache
func (r *Resolver) Lookup(address string) ([]net.IP, error) {
	ips, err := net.LookupIP(address)
	if err != nil {
		return nil, err
	}

	v4s := make([]net.IP, 0, len(ips))
	for _, ip := range ips {
		if ip.To4() != nil {
			v4s = append(v4s, ip)
		}
	}

	ttl, ok := r.ttls[address]
	if ok == false {
		ttl = r.defaultTTL
	}
	expires := time.Now().Add(ttl)
	r.Lock()
	r.cache[address] = &value{
		ips:     ips,
		ipv4s:   v4s,
		expires: expires,
	}
	r.Unlock()
	return ips, nil
}
开发者ID:karlseguin,项目名称:dnscache,代码行数:28,代码来源:dnscache.go

示例15: safeAddr

func safeAddr(hostport string) (string, error) {
	host, port, err := net.SplitHostPort(hostport)
	if err != nil {
		return "", err
	}

	ip := net.ParseIP(host)
	if ip != nil {
		if ip.To4() != nil && isBadIPv4(ip) {
			return "", fmt.Errorf("bad ip is detected: %v", ip)
		}
		return net.JoinHostPort(ip.String(), port), nil
	}

	if isBadHost(host) {
		return "", fmt.Errorf("bad host is detected: %v", host)
	}

	ips, err := net.LookupIP(host) // TODO timeout
	if err != nil || len(ips) <= 0 {
		return "", err
	}
	for _, ip := range ips {
		if ip.To4() != nil && isBadIPv4(ip) {
			return "", fmt.Errorf("bad ip is detected: %v", ip)
		}
	}
	return net.JoinHostPort(ips[0].String(), port), nil
}
开发者ID:hakobe,项目名称:paranoidhttp,代码行数:29,代码来源:client.go


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