Ejemplo n.º 1
0
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
}
Ejemplo n.º 2
0
/* 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)
}
Ejemplo n.º 3
0
// 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
}
Ejemplo n.º 4
0
// 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")
}
Ejemplo n.º 5
0
Archivo: zone.go Proyecto: richtr/mdns
// 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
}
Ejemplo n.º 6
0
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()

}
Ejemplo n.º 7
0
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
}
Ejemplo n.º 8
0
// 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")
}
Ejemplo n.º 9
0
// 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
}
Ejemplo n.º 10
0
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)
}
Ejemplo n.º 11
0
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)
}
Ejemplo n.º 12
0
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)
	}
}
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})
}
Ejemplo n.º 14
0
// 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
}
Ejemplo n.º 15
0
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
}
Ejemplo n.º 16
0
// Initialize base parser libary and start handler
func init() {
	// initialize pacparser library
	C.pacparser_init()
	// deprecated function in newer library versions
	// and simply returns without taking any action
	C.pacparser_enable_microsoft_extensions()
	// set error handler
	C.pacparser_set_error_printer(C.pacparser_error_printer(C.bufferErrors))
	// build channels
	parsePacChannel = make(chan *parsePacRequest, 100)
	findProxyChannel = make(chan *findProxyRequest, 100)
	// set default ip
	myIpDefault = "127.0.0.1"
	// attempt to find local hostname
	if host, err := os.Hostname(); err == nil {
		// attempt to resolve returned host
		if addrs, err := net.LookupIP(host); err == nil {
			// loop over resolved addresses
			for _, addr := range addrs {
				if !addr.IsLoopback() {
					// set default ip address
					myIpDefault = addr.String()
					// break after first valid address
					break
				}
			}
		}
	}
	// spawn handler
	go parseHandler()
}
Ejemplo n.º 17
0
func (c Config) Bootstrap() []net.UDPAddr {
	var udpaddrs []net.UDPAddr
	for _, s := range c.B {
		z := strings.SplitN(s, ":", 2)
		if len(z) != 2 {
			continue
		}
		host := z[0]
		var begin, end uint16
		_, err := fmt.Sscanf(z[1], "%d-%d", &begin, &end)
		if err == nil && begin < end {
			addrs, err := net.LookupIP(host)
			if err == nil {
				for _, a := range addrs {
					for p := begin; p <= end; p++ {
						addr := net.UDPAddr{
							Port: int(p),
							IP:   a,
						}
						udpaddrs = append(udpaddrs, addr)
					}
				}
			}
		}
	}
	return udpaddrs
}
Ejemplo n.º 18
0
// This looks up a TeamSpeak host, immitating the manner in which the TeamSpeak
// client looks it up. hostCombo should either be a host:port combination or a
// lone hostname. If a port is not specified, the default port of 9987 will be
// used.
func ResolveHost(hostCombo string) ([]string, error) {
	hostname, port, err := net.SplitHostPort(hostCombo)
	if addrErr, ok := err.(*net.AddrError); ok && addrErr.Err == "missing port in address" {
		hostname = hostCombo
		port = "9987"
	} else if err != nil {
		return nil, err
	}

	_, records, err := net.LookupSRV("ts3", "udp", hostname)
	if err != nil {
		return nil, err
	}

	if len(records) > 0 {
		hosts := make([]string, len(records))
		for i, record := range records {
			hosts[i] = net.JoinHostPort(record.Target, strconv.FormatInt(int64(record.Port), 10))
		}

		return hosts, nil
	}

	addrs, err := net.LookupIP(hostname)
	if err != nil {
		return nil, err
	}

	hosts := make([]string, len(addrs))
	for i, addr := range addrs {
		hosts[i] = net.JoinHostPort(addr.String(), port)
	}

	return hosts, nil
}
Ejemplo n.º 19
0
func TestAddTarget(t *testing.T) {
	pingbeat := Pingbeat{}
	pingbeat.ipv4targets = make(map[string][2]string)
	pingbeat.ipv6targets = make(map[string][2]string)

	// test adding target as IP address
	name := "192.168.1.1"
	addr := name
	tag := "target_as_addr"
	pingbeat.AddTarget(name, tag)
	assert.Equal(t, name, pingbeat.ipv4targets[addr][0])
	assert.Equal(t, tag, pingbeat.ipv4targets[addr][1])

	// test adding target as a DNS name
	name = "elastic.co"
	tag = "target_as_name"
	addrs, err := net.LookupIP(name)
	if err != nil {
		t.Logf("Failed to resolve %s to IP address!", name)
		t.Fail()
	} else {
		addr := addrs[0].String()
		pingbeat.AddTarget(name, tag)
		assert.Equal(t, name, pingbeat.ipv4targets[addr][0])
		assert.Equal(t, tag, pingbeat.ipv4targets[addr][1])
	}
}
func dataSourceDnsARecordRead(d *schema.ResourceData, meta interface{}) error {
	host := d.Get("host").(string)

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

	addrs := make([]string, 0)

	for _, ip := range records {
		// LookupIP returns A (IPv4) and AAAA (IPv6) records
		// Filter out AAAA records
		if ipv4 := ip.To4(); ipv4 != nil {
			addrs = append(addrs, ipv4.String())
		}
	}

	sort.Strings(addrs)

	d.Set("addrs", addrs)
	d.SetId(host)

	return nil
}
Ejemplo n.º 21
0
func (t *UpstreamTransport) lookupIp() (addr *net.TCPAddr, err error) {
	// Cached tcpaddr
	if t.tcpaddr != nil && (t.DNSCacheDuration == 0 || t.tcpaddrCacheTime.Add(t.DNSCacheDuration).After(time.Now())) {
		return t.tcpaddr, nil
	}

	ips, err := net.LookupIP(t.host)
	var ip net.IP = nil

	if err != nil {
		return nil, err
	}

	// Find first IPv4 IP
	for i := range ips {
		ip = ips[i].To4()
		if ip != nil {
			break
		}
	}

	if ip != nil {
		t.tcpaddr = &net.TCPAddr{}
		t.tcpaddr.Port = t.port
		t.tcpaddr.IP = ip
		t.tcpaddrCacheTime = time.Now()
		addr = t.tcpaddr
	} else {
		errstr := fmt.Sprintf("Can't get IP addr for %v: %v", t.host, err)
		err = errors.New(errstr)
	}

	return
}
Ejemplo n.º 22
0
func NewDatadogStats(datadogHost string) (*DatadogStats, error) {
	var ip net.IP = nil
	var err error = nil

	// Assume datadogHost is an IP and try to parse it
	ip = net.ParseIP(datadogHost)

	// Parsing failed
	if ip == nil {
		ips, _ := net.LookupIP(datadogHost)

		if len(ips) > 0 {
			ip = ips[0]
		}
	}

	if ip != nil {
		gdsp, err := godspeed.New(ip.String(), godspeed.DefaultPort, false)
		if err == nil {
			return &DatadogStats{gdsp}, nil
		}
	}

	return nil, err
}
Ejemplo n.º 23
0
func GetNodeIP(nodeName string) (string, error) {
	ip := net.ParseIP(nodeName)
	if ip == nil {
		addrs, err := net.LookupIP(nodeName)
		if err != nil {
			return "", fmt.Errorf("Failed to lookup IP address for node %s: %v", nodeName, err)
		}
		for _, addr := range addrs {
			// Skip loopback and non IPv4 addrs
			if addr.IsLoopback() || addr.To4() == nil {
				glog.V(5).Infof("Skipping loopback/non-IPv4 addr: %q for node %s", addr.String(), nodeName)
				continue
			}
			ip = addr
			break
		}
	} else if ip.IsLoopback() || ip.To4() == nil {
		glog.V(5).Infof("Skipping loopback/non-IPv4 addr: %q for node %s", ip.String(), nodeName)
		ip = nil
	}

	if ip == nil || len(ip.String()) == 0 {
		return "", fmt.Errorf("Failed to obtain IP address from node name: %s", nodeName)
	}
	return ip.String(), nil
}
Ejemplo n.º 24
0
// NodeAddresses returns the NodeAddresses of the instance with the specified nodeName.
func (v *OVirtCloud) NodeAddresses(nodeName types.NodeName) ([]api.NodeAddress, error) {
	name := mapNodeNameToInstanceName(nodeName)
	instance, err := v.fetchInstance(name)
	if err != nil {
		return nil, err
	}

	var address net.IP

	if instance.IPAddress != "" {
		address = net.ParseIP(instance.IPAddress)
		if address == nil {
			return nil, fmt.Errorf("couldn't parse address: %s", instance.IPAddress)
		}
	} else {
		resolved, err := net.LookupIP(name)
		if err != nil || len(resolved) < 1 {
			return nil, fmt.Errorf("couldn't lookup address: %s", name)
		}
		address = resolved[0]
	}

	return []api.NodeAddress{
		{Type: api.NodeLegacyHostIP, Address: address.String()},
		{Type: api.NodeInternalIP, Address: address.String()},
		{Type: api.NodeExternalIP, Address: address.String()},
	}, nil
}
Ejemplo n.º 25
0
Archivo: span.go Proyecto: jllopis/kit
// makeEndpoint will return a nil Endpoint if the input parameters are
// malformed.
func makeEndpoint(hostport, serviceName string) *zipkincore.Endpoint {
	host, port, err := net.SplitHostPort(hostport)
	if err != nil {
		Log.Log("hostport", hostport, "err", err)
		return nil
	}
	addrs, err := net.LookupIP(host)
	if err != nil {
		Log.Log("host", host, "err", err)
		return nil
	}
	if len(addrs) <= 0 {
		Log.Log("host", host, "err", "no IPs")
		return nil
	}
	portInt, err := strconv.ParseInt(port, 10, 16)
	if err != nil {
		Log.Log("port", port, "err", err)
		return nil
	}
	endpoint := zipkincore.NewEndpoint()
	binary.LittleEndian.PutUint32(addrs[0], (uint32)(endpoint.Ipv4))
	endpoint.Port = int16(portInt)
	endpoint.ServiceName = serviceName
	return endpoint
}
Ejemplo n.º 26
0
func main() {
	fmt.Println("Welcome to a Go program called Name2.")
	fmt.Println("What's your name?")
	fmt.Scanln(&name)
	fmt.Println("Interesting name,", name, ",do you know what it means?")
Ask:
	fmt.Scanln(&answer)
	posAnswers := []string{"y", "Y", "yes", "Yes", "YES", "ja"}
	negAnswers := []string{"n", "N", "no", "No", "NO"}
	bsAnswers := []string{"blerg", "kinda", "pissoff", "smartass"}
	if containsString(posAnswers, answer) {
		fmt.Println("Oh really?")
		goto Ask
	} else if containsString(negAnswers, answer) {
		fmt.Println("Well let me look it up!")
		goto Query
	} else if containsString(bsAnswers, answer) {
		fmt.Println("Piss off type y/n, smart ass")
		goto Ask
	} else {
		fmt.Println("Please type yes or no, then press Enter.")
		goto Ask
	}
Query:
	fmt.Println("Enter host:")
	fmt.Scanln(&host)
	fmt.Println("Scanning the internets.")
	ip, _ := net.LookupIP(host)
	fmt.Println(ip)
	goto Query
}
Ejemplo n.º 27
0
func googleAddr(c *icmp.PacketConn, protocol int) (net.Addr, error) {
	const host = "www.google.com"
	ips, err := net.LookupIP(host)
	if err != nil {
		return nil, err
	}
	netaddr := func(ip net.IP) (net.Addr, error) {
		switch c.LocalAddr().(type) {
		case *net.UDPAddr:
			return &net.UDPAddr{IP: ip}, nil
		case *net.IPAddr:
			return &net.IPAddr{IP: ip}, nil
		default:
			return nil, errors.New("neither UDPAddr nor IPAddr")
		}
	}
	for _, ip := range ips {
		switch protocol {
		case iana.ProtocolICMP:
			if ip.To4() != nil {
				return netaddr(ip)
			}
		case iana.ProtocolIPv6ICMP:
			if ip.To16() != nil && ip.To4() == nil {
				return netaddr(ip)
			}
		}
	}
	return nil, errors.New("no A or AAAA record")
}
Ejemplo n.º 28
0
func Dial(dest v2net.Destination) (net.Conn, error) {
	var ip net.IP
	if dest.Address().IsIPv4() || dest.Address().IsIPv6() {
		ip = dest.Address().IP()
	} else {
		ips, err := net.LookupIP(dest.Address().Domain())
		if err != nil {
			return nil, err
		}
		if len(ips) == 0 {
			return nil, ErrInvalidHost
		}
		ip = ips[dice.Roll(len(ips))]
	}
	if dest.IsTCP() {
		return net.DialTCP("tcp", nil, &net.TCPAddr{
			IP:   ip,
			Port: int(dest.Port()),
		})
	} else {
		return net.DialUDP("udp", nil, &net.UDPAddr{
			IP:   ip,
			Port: int(dest.Port()),
		})
	}
}
Ejemplo n.º 29
0
func (p *Pingbeat) AddTarget(target string, tag string) {
	if addr := net.ParseIP(target); addr.String() == "" {
		if addr.To4() != nil {
			logp.Debug("pingbeat", "IPv4: %s\n", addr.String())
			p.ipv4targets[addr.String()] = [2]string{target, tag}
		} else {
			logp.Debug("pingbeat", "IPv6: %s\n", addr.String())
			p.ipv6targets[addr.String()] = [2]string{target, tag}
		}
	} else {
		logp.Debug("pingbeat", "Getting IP addresses for %s:\n", target)
		addrs, err := net.LookupIP(target)
		if err != nil {
			logp.Warn("Failed to resolve %s to IP address, ignoring this target.\n", target)
		} else {
			for j := 0; j < len(addrs); j++ {
				if addrs[j].To4() != nil {
					logp.Debug("pingbeat", "IPv4: %s\n", addrs[j].String())
					p.ipv4targets[addrs[j].String()] = [2]string{target, tag}
				} else {
					logp.Debug("pingbeat", "IPv6: %s\n", addrs[j].String())
					p.ipv6targets[addrs[j].String()] = [2]string{target, tag}
				}
			}
		}
	}
}
Ejemplo n.º 30
0
func (c *DNSCache) ResolveAll(host string) (ips []net.IP, err error) {
	c.m.Lock()
	defer c.m.Unlock()

	ips = c.cache[host]
	if ips != nil {
		return
	}

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

	ips = make([]net.IP, 0, len(aips))
	for _, ip := range aips {
		if ip.To4() != nil {
			if c.SkipIPv4 {
				continue
			}
		} else {
			if c.SkipIPv6 {
				continue
			}
		}
		ips = append(ips, ip)
	}
	c.cache[host] = ips
	return
}