Ejemplo n.º 1
0
func IvsOffLine() {

	info, _ = net.InterfaceAddrs()
	ipx = strings.Split(info[0].String(), "/")[0]
	//fmt.Println(ipx)
	if ipx == "0.0.0.0" {
		fmt.Println("network problem....")
		fmt.Println(strings.Split(info[0].String(), "/")[0])
		for strings.Split(info[0].String(), "/")[0] == "0.0.0.0" {
			time.Sleep(time.Second * 5)
			info, _ = net.InterfaceAddrs()
		}
		fmt.Println("network problem fixed.. alarm will restart in 1 min")
		time.Sleep(time.Second * 30)
		geturl = "http://" + strings.Split(info[0].String(), "/")[0] + "/refresh"
		request, _ = http.NewRequest("GET", geturl, nil)
		resp, _ = client.Do(request)
		fmt.Println(resp)
		time.Sleep(time.Second * 2)
		fmt.Println("alarm begin..")
		geturl = "http://" + strings.Split(info[0].String(), "/")[0] + "/alarmbegin"
		request, _ = http.NewRequest("GET", geturl, nil)
		resp, _ = client.Do(request)
		fmt.Println(resp)
		fmt.Println("done..")
	}

}
Ejemplo n.º 2
0
func main() {
	network := false
	master := false
	var i uint64 = 0
	port := ":12332"
	ipAdd, _ := net.InterfaceAddrs()
	fmt.Println(strings.Split(ipAdd[1].String(), "/")[0])

	for !network {
		ipAdd, _ := net.InterfaceAddrs()
		ip := strings.Split(ipAdd[1].String(), "/")[0]
		if ip != "::1" {
			network = true

		}
	}

	udpConn, addr := ClientConnectUDP(port)

	time.Sleep(time.Second * 1)
	buffer := make([]byte, 8)

	for !(master) {
		udpConn.SetReadDeadline(time.Now().Add(time.Second * 2))
		n, _, err := udpConn.ReadFromUDP(buffer)

		if err == nil {
			i = binary.BigEndian.Uint64(buffer[0:n])

		} else {

			master = true
			fmt.Println("Master has given Dobby a sock. Dobby is a free elf!...")
			time.Sleep(time.Second * 1)
		}
	}
	udpConn.Close()

	startBackup()

	udpConn, _ = net.DialUDP("udp", nil, addr)

	for {
		fmt.Println(i)
		i++
		ClientSend(i, udpConn, buffer)

	}
}
Ejemplo n.º 3
0
// getFirstLocalIPAddr returns the first available IP address of the local machine
// This is a fix for Beaglebone Black where net.LookupIP(hostname) return no IP address.
func getFirstLocalIPAddr() (net.IP, error) {
	addrs, err := net.InterfaceAddrs()
	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
		}
		if ip == nil || ip.IsLoopback() || ip.IsUnspecified() {
			continue
		}
		ip = ip.To4()
		if ip == nil {
			continue // not an ipv4 address
		}
		return ip, nil
	}

	return nil, errors.New("Could not determine ip address")
}
Ejemplo n.º 4
0
func main() {
	ParseArgs()
	CurrentWorld = GenerateWorld()

	http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets"))))
	http.HandleFunc("/", DisplayChunk)
	http.HandleFunc("/ws", SocketHandle)

	addrs, err := net.InterfaceAddrs()
	if err != nil {
		LogStatusFatal(err)
	}

	var ip string
	if runtime.GOOS == "windows" {
		ip = strings.Split(fmt.Sprintf("%v", addrs[3]), "/")[0]
	} else {
		ip = strings.Split(fmt.Sprintf("%v", addrs[4]), "/")[0]
	}
	LogStatus("Running Server At: " + ip + ":" + Port)

	err = http.ListenAndServe(ip+":"+Port, nil)
	if err != nil {
		LogStatusFatal(err)
	}
}
Ejemplo n.º 5
0
// Generate all publishable URLs for a given HTTP port.
func interfaceURLs(port int) (types.URLs, error) {
	allAddrs, err := net.InterfaceAddrs()
	if err != nil {
		return []url.URL{}, err
	}

	var allURLs types.URLs
	for _, a := range allAddrs {
		ip, ok := a.(*net.IPNet)
		if !ok || !ip.IP.IsGlobalUnicast() {
			continue
		}

		tcp := net.TCPAddr{
			IP:   ip.IP,
			Port: port,
		}

		u := url.URL{
			Scheme: "http",
			Host:   tcp.String(),
		}
		allURLs = append(allURLs, u)
	}

	if len(allAddrs) == 0 {
		return []url.URL{}, fmt.Errorf("no publishable addresses")
	}

	return allURLs, nil
}
Ejemplo n.º 6
0
func (cm *connMetadata) localhost() net.Addr {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		panic(err)
	}
	return addrs[0]
}
Ejemplo n.º 7
0
// Can't use localhost here since go has a special case to not use proxy if connecting to localhost
// See https://golang.org/pkg/net/http/#ProxyFromEnvironment
func (s *DockerDaemonSuite) TestCLIProxyProxyTCPSock(c *check.C) {
	testRequires(c, SameHostDaemon)
	// get the IP to use to connect since we can't use localhost
	addrs, err := net.InterfaceAddrs()
	c.Assert(err, checker.IsNil)
	var ip string
	for _, addr := range addrs {
		sAddr := addr.String()
		if !strings.Contains(sAddr, "127.0.0.1") {
			addrArr := strings.Split(sAddr, "/")
			ip = addrArr[0]
			break
		}
	}

	c.Assert(ip, checker.Not(checker.Equals), "")

	s.d.Start(c, "-H", "tcp://"+ip+":2375")

	icmd.RunCmd(icmd.Cmd{
		Command: []string{dockerBinary, "info"},
		Env:     []string{"DOCKER_HOST=tcp://" + ip + ":2375", "HTTP_PROXY=127.0.0.1:9999"},
	}).Assert(c, icmd.Expected{Error: "exit status 1", ExitCode: 1})
	// Test with no_proxy
	icmd.RunCmd(icmd.Cmd{
		Command: []string{dockerBinary, "info"},
		Env:     []string{"DOCKER_HOST=tcp://" + ip + ":2375", "HTTP_PROXY=127.0.0.1:9999", "NO_PROXY=" + ip},
	}).Assert(c, icmd.Success)
}
Ejemplo n.º 8
0
// print interfaces to know where the proxy is listening
func printInterfaces() {
	addrs, err := net.InterfaceAddrs()

	if err != nil {
		fmt.Println("Can't get interfaces. You have to have at least one network connection.")
		log.Fatal("No interface found")
	}

	for _, addr := range addrs {

		var ip net.IP
		switch v := addr.(type) {
		case *net.IPAddr:
		case *net.IPNet:
			ip = v.IP
		}

		if ip == nil || ip.IsLoopback() {
			continue
		}

		ip = ip.To4()
		if ip == nil {
			continue // not an ipv4 address
		}
		fmt.Println("http://" + ip.String() + Config.Service.Listen)
	}
}
Ejemplo n.º 9
0
func printAddressAndPort() {
	addrs, err := net.InterfaceAddrs()

	if err != nil {
		log.Fatal("Error getting local address", err)
	}

	var localAddress string = "<your-local-ip-address>"
	for _, address := range addrs {
		// check the address type and if it is not a loopback then display it
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				localAddress = ipnet.IP.String()
			}
		}
	}

	fmt.Println()
	if insecure {
		fmt.Printf("Use this address: http://%s:%v\n (No secret username required)", localAddress, port)
	} else {
		fmt.Printf("Use this address: http://%s:%v\n (Enter %s for username when requested. Ignore password) \n", localAddress, port, secretUsername)
	}
	fmt.Println()

}
Ejemplo n.º 10
0
func printServerMsg(serverConf *http.Server) {
	host, port, e := net.SplitHostPort(serverConf.Addr)
	fatalIf(probe.NewError(e), "Unable to split host port.", nil)

	var hosts []string
	switch {
	case host != "":
		hosts = append(hosts, host)
	default:
		addrs, e := net.InterfaceAddrs()
		fatalIf(probe.NewError(e), "Unable to get interface address.", nil)

		for _, addr := range addrs {
			if addr.Network() == "ip+net" {
				host := strings.Split(addr.String(), "/")[0]
				if ip := net.ParseIP(host); ip.To4() != nil {
					hosts = append(hosts, host)
				}
			}
		}
	}
	for _, host := range hosts {
		if serverConf.TLSConfig != nil {
			Printf("    https://%s:%s\n", host, port)
		} else {
			Printf("    http://%s:%s\n", host, port)
		}
	}
}
Ejemplo n.º 11
0
func ComposeProfile() (profile *Client, err error) {
	profile = new(Client)
	profile.Name = conf.CLIENT_NAME
	profile.Group = conf.CLIENT_GROUP
	profile.CPUs = runtime.NumCPU()

	//app list
	profile.Apps = []string{}
	if conf.SUPPORTED_APPS != "" { //apps configured in .cfg
		apps := strings.Split(conf.SUPPORTED_APPS, ",")
		for _, item := range apps {
			profile.Apps = append(profile.Apps, item)
		}
	} else { //apps not configured in .cfg, check the executables in APP_PATH)
		if files, err := ioutil.ReadDir(conf.APP_PATH); err == nil {
			for _, item := range files {
				profile.Apps = append(profile.Apps, item.Name())
			}
		}
	}

	if addrs, err := net.InterfaceAddrs(); err == nil {
		for _, a := range addrs {
			if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() && len(strings.Split(ipnet.IP.String(), ".")) == 4 {
				profile.Host = ipnet.IP.String()
				break
			}
		}
	}
	return
}
Ejemplo n.º 12
0
func (a *syslogAppender) calculateHostname() string {
	if a.hostname != "" {
		return a.hostname
	}

	// try to get local IP
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		// unlikely to happen, but nothing we can do
	}
	for _, address := range addrs {
		// check the address type and if it is not a loopback the display it
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				a.hostname = ipnet.IP.String()
				return a.hostname
			}
		}
	}

	// try to use hostname if we can't get an IP addr
	host, err := os.Hostname()
	if err == nil {
		a.hostname = host
		return a.hostname
	}

	// everything failed. just put something in a.addr so we don't call method over and over
	a.hostname = "unknown-host"
	return a.hostname
}
Ejemplo n.º 13
0
// This returns the list of local ip addresses which other hosts can connect
// to (NOTE: Loopback ip is ignored).
// Also resolves Hostname to an address and adds it to the list too, so
// IPs from /etc/hosts can work too.
func GetLocalIPs() ([]*net.IP, error) {
	hostname, err := os.Hostname()
	if err != nil {
		return nil, errors.Wrap(err, "Failed to lookup hostname")
	}
	// Resolves IP Address from Hostname, this way overrides in /etc/hosts
	// can work too for IP resolution.
	ipInfo, err := net.ResolveIPAddr("ip4", hostname)
	if err != nil {
		return nil, errors.Wrap(err, "Failed to resolve ip")
	}
	ips := []*net.IP{&ipInfo.IP}

	// TODO(zviad): Is rest of the code really necessary?
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return nil, errors.Wrap(err, "Failed to get interface addresses.")
	}
	for _, addr := range addrs {
		ipnet, ok := addr.(*net.IPNet)
		if !ok {
			continue
		}

		if ipnet.IP.IsLoopback() {
			continue
		}

		ips = append(ips, &ipnet.IP)
	}
	return ips, nil
}
Ejemplo n.º 14
0
func defaultWorkId() (uint16, error) {
	var buf bytes.Buffer
	interfaces, err := net.Interfaces()
	if err != nil {
		fmt.Println(err)
		return 0, err
	}
	for _, inter := range interfaces {
		buf.Write(inter.HardwareAddr)
		buf.WriteByte(byte(0))
	}

	//fmt.Println("-------------------")

	inter2, err := net.InterfaceAddrs()
	if err != nil {
		fmt.Println(err)
		return 0, err
	}
	for _, i2 := range inter2 {
		buf.WriteString(i2.String())
		buf.WriteByte(byte(0))
	}

	buf.WriteString(strconv.Itoa(os.Getpid()))

	bs := md5.Sum(buf.Bytes())
	//fmt.Println(bs)

	//挑选16个字节的md5只的第1和第9个
	ret := uint16(bs[0])<<8 + uint16(bs[8])
	//fmt.Println(ret)

	return ret, nil
}
Ejemplo n.º 15
0
// GetExternalIP tries to determine the external IP address
// used on this host.
func GetExternalIP() string {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		panic(err)
	}

	valid := []string{}

	for _, a := range addrs {
		if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			addr := ipnet.IP.String()
			match := validIPv4addr.FindStringSubmatch(addr)
			if match != nil {
				if addr != "127.0.0.1" {
					valid = append(valid, addr)
				}
			}
		}
	}
	switch len(valid) {
	case 0:
		return "127.0.0.1"
	case 1:
		return valid[0]
	default:
		// try to get a routable ip if possible.
		for _, ip := range valid {
			if IsRoutableIPv4(ip) {
				return ip
			}
		}
		// give up, just return the first.
		return valid[0]
	}
}
Ejemplo n.º 16
0
// Can't use localhost here since go has a special case to not use proxy if connecting to localhost
// See https://golang.org/pkg/net/http/#ProxyFromEnvironment
func (s *DockerDaemonSuite) TestCliProxyProxyTCPSock(c *check.C) {
	testRequires(c, SameHostDaemon)
	// get the IP to use to connect since we can't use localhost
	addrs, err := net.InterfaceAddrs()
	c.Assert(err, checker.IsNil)
	var ip string
	for _, addr := range addrs {
		sAddr := addr.String()
		if !strings.Contains(sAddr, "127.0.0.1") {
			addrArr := strings.Split(sAddr, "/")
			ip = addrArr[0]
			break
		}
	}

	c.Assert(ip, checker.Not(checker.Equals), "")

	err = s.d.Start("-H", "tcp://"+ip+":2375")
	c.Assert(err, checker.IsNil)
	cmd := exec.Command(dockerBinary, "info")
	cmd.Env = []string{"DOCKER_HOST=tcp://" + ip + ":2375", "HTTP_PROXY=127.0.0.1:9999"}
	out, _, err := runCommandWithOutput(cmd)
	c.Assert(err, checker.NotNil, check.Commentf("%v", out))
	// Test with no_proxy
	cmd.Env = append(cmd.Env, "NO_PROXY="+ip)
	out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "info"))
	c.Assert(err, checker.IsNil, check.Commentf("%v", out))
}
Ejemplo n.º 17
0
func TestRegisterIPResources(t *testing.T) {

	var ipResult dao.HostIPs
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		t.Fatalf("Error readin addresses %v", err)
	}
	fn := func(ips dao.HostIPs, unused *int) error {
		ipResult = ips
		return nil
	}
	registerIPs("testId", fn)

	if len(addrs) != len(ipResult.IPs) {
		t.Fatalf("IP addresse length differed %v and %v", addrs, ipResult.IPs)
	}

	if ipResult.HostId != "testId" {
		t.Fatalf("Expected host id %v, got %v", ipResult.HostId, "testId")
	}

	//make a lookup map (set) of result IPs
	resultIps := make(map[string]bool)
	for _, ip := range ipResult.IPs {
		resultIps[ip.IPAddress] = true
	}
	//now see if IPs match IPs from std lib
	for _, addr := range addrs {
		_, ok := resultIps[addr.String()]
		if !ok {
			t.Fatalf("IP %v not find in %v", addr, ipResult)
		}
	}
}
Ejemplo n.º 18
0
// checkInterfaces - see if listener is bound to correct interface.
// first is localhost, second should be IP4 of active card,
// third is IP6 localhost, fourth is IP6 for active card (on this system)
func checkInterfaces() {
	ifa, err := net.InterfaceAddrs()
	if err != nil {
		fmt.Printf("Can't list interfaces\n")
		os.Exit(1)
	}
	fmt.Printf("Interfaces (ifa[]) = %v\n", ifa)
	if len(ifa) < 2 {
		fmt.Printf("Can't list interfaces\n")
		os.Exit(1)
	}
	// check IP4 of active card
	fmt.Printf("ifa[] = %v\n", ifa)
	var myIfs []string
	if wantLocal {
		myIfs = strings.Split(ifa[0].String(), "/")
	} else {
		myIfs = strings.Split(ifa[1].String(), "/")
	}
	fmt.Printf("myIfs = %v\n", myIfs)
	myIf := myIfs[0]
	fmt.Printf("myIf = %v\n", myIf)
	if myIf != hostIPstr {
		log.Printf("Wanted %s got %s\n", hostIPstr, myIf)
		log.Fatalf("handler bound to wrong interface")

	}
}
Ejemplo n.º 19
0
func resolveAddrListOrPatterns(strs []string, expand bool) (addrs AddrList, err error) {
	var str string

	defer func() {
		if r := recover(); r != nil {
			err = &AddrError{str, r.(error)}
		}
	}()

	for _, str = range strs {
		host, port := splitAddr(str)

		if expand && host == "" {
			ips, err := net.InterfaceAddrs()
			if err != nil {
				panic(err)
			}

			for _, ip := range ips {
				addrs = addrs.AddResolved(ip.(*net.IPNet).IP.String(), port)
			}
		} else {
			addrs = addrs.AddResolved(host, port)
		}
	}

	return
}
Ejemplo n.º 20
0
// getInterfaceIPv4s is synonymous to net.InterfaceAddrs()
// returns net.IP IPv4 only representation of the net.Addr.
// Additionally the returned list is sorted by their last
// octet value.
//
// [The logic to sort by last octet is implemented to
// prefer CIDRs with higher octects, this in-turn skips the
// localhost/loopback address to be not preferred as the
// first ip on the list. Subsequently this list helps us print
// a user friendly message with appropriate values].
func getInterfaceIPv4s() ([]net.IP, error) {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return nil, fmt.Errorf("Unable to determine network interface address. %s", err)
	}
	// Go through each return network address and collate IPv4 addresses.
	var nips []net.IP
	for _, addr := range addrs {
		if addr.Network() == "ip+net" {
			var nip net.IP
			// Attempt to parse the addr through CIDR.
			nip, _, err = net.ParseCIDR(addr.String())
			if err != nil {
				return nil, fmt.Errorf("Unable to parse addrss %s, error %s", addr, err)
			}
			// Collect only IPv4 addrs.
			if nip.To4() != nil {
				nips = append(nips, nip)
			}
		}
	}
	// Sort the list of IPs by their last octet value.
	sort.Sort(sort.Reverse(byLastOctetValue(nips)))
	return nips, nil
}
Ejemplo n.º 21
0
func doesipv6() bool {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return false
	}
	localipv6 := []string{"fc00::/7", "::1/128", "fe80::/10"}

	for _, a := range addrs {
		if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			ip6 := ipnet.IP.To16()
			ip4 := ipnet.IP.To4()
			if ip6 != nil && ip4 == nil {
				local := false
				for _, r := range localipv6 {
					_, cidr, _ := net.ParseCIDR(r)
					if cidr.Contains(ip6) {
						local = true
					}
				}
				if !local {
					return true
				}
			}
		}
	}
	return false
}
Ejemplo n.º 22
0
func VisitIps(port int) {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	log.Println("Possible visit :")
	index := 1

	ips := make([]string, len(addrs))

	for _, addr := range addrs {
		if ip, ok := addr.(*net.IPNet); ok && !ip.IP.IsLoopback() {
			if ip.IP.To4() != nil {
				ipstr := ip.IP.String()
				ips[index-1] = ipstr
				fmt.Printf("%-5d http://%s:%d\n", index, ipstr, port)
				index++
			}
		}
	}
	infos := GenQRCodeByAddr(&ips, port)
	//show images
	for addr, filename := range *infos {
		//don't use third program
		// go ShowImage(addr, filename)
		go ShowPng(addr, filename)
	}
}
Ejemplo n.º 23
0
// getRPCServer instance
func getRPCServer(rpcHandler http.Handler) (*http.Server, *probe.Error) {
	// Minio server config
	httpServer := &http.Server{
		Addr:           ":9001", // TODO make this configurable
		Handler:        rpcHandler,
		MaxHeaderBytes: 1 << 20,
	}
	var hosts []string
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return nil, probe.NewError(err)
	}
	for _, addr := range addrs {
		if addr.Network() == "ip+net" {
			host := strings.Split(addr.String(), "/")[0]
			if ip := net.ParseIP(host); ip.To4() != nil {
				hosts = append(hosts, host)
			}
		}
	}
	for _, host := range hosts {
		fmt.Printf("Starting minio server on: http://%s:9001/rpc, PID: %d\n", host, os.Getpid())
	}
	return httpServer, nil
}
Ejemplo n.º 24
0
// LookupPeers busca peers en la red
func LookupPeers() <-chan []string {
	entriesCh := make(chan *mdns.ServiceEntry, 4)
	resChan := make(chan []string, 1)
	go func(ch chan<- []string) {
		var entries []string             // peers
		addrs, _ := net.InterfaceAddrs() // interfaces locales
		for entry := range entriesCh {
			addr := entry.AddrV4 // dirección de host encontrado
			skip := false        // saltar o no esta dirección
			// buscar si peer encontrado es máquina propia
			for i := range addrs {
				n := addrs[i].(*net.IPNet) // hacer type assertion
				if n.IP.Equal(addr) {
					skip = true
				}
			}
			if !skip {
				entries = append(entries, net.JoinHostPort(addr.String(),
					fmt.Sprintf("%d", entry.Port)))
			}
		}
		resChan <- entries
	}(resChan)
	mdns.Lookup("_flow._tcp", entriesCh)
	close(entriesCh)
	return resChan
}
Ejemplo n.º 25
0
// Validate given node IP belongs to the current host
func (kl *Kubelet) validateNodeIP() error {
	if kl.nodeIP == nil {
		return nil
	}

	// Honor IP limitations set in setNodeStatus()
	if kl.nodeIP.IsLoopback() {
		return fmt.Errorf("nodeIP can't be loopback address")
	}
	if kl.nodeIP.To4() == nil {
		return fmt.Errorf("nodeIP must be IPv4 address")
	}

	addrs, err := net.InterfaceAddrs()
	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.Equal(kl.nodeIP) {
			return nil
		}
	}
	return fmt.Errorf("Node IP: %q not found in the host's network interfaces", kl.nodeIP.String())
}
Ejemplo n.º 26
0
func (r *ReplicaSet) proxyHostname() string {
	const home = "127.0.0.1"

	hostname, err := os.Hostname()
	if err != nil {
		r.Log.Error(err)
		return home
	}

	// The follow logic ensures that the hostname resolves to a local address.
	// If it doesn't we don't use it since it probably wont work anyways.
	hostnameAddrs, err := net.LookupHost(hostname)
	if err != nil {
		r.Log.Error(err)
		return home
	}

	interfaceAddrs, err := net.InterfaceAddrs()
	if err != nil {
		r.Log.Error(err)
		return home
	}

	for _, ia := range interfaceAddrs {
		sa := ia.String()
		for _, ha := range hostnameAddrs {
			// check for an exact match or a match ignoring the suffix bits
			if sa == ha || strings.HasPrefix(sa, ha+"/") {
				return hostname
			}
		}
	}
	r.Log.Warnf("hostname %s doesn't resolve to the current host", hostname)
	return home
}
Ejemplo n.º 27
0
// 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")
}
Ejemplo n.º 28
0
// Returns all local interface IP addresses in the private network range
// They are traversed in the order returned by `net.InterfaceAddrs()`
func localPrivateAddrs() (ret []*net.UDPAddr) {
	addrs, err := net.InterfaceAddrs()
	if err == nil {
		for i := 0; i < len(addrs); i++ {
			var ip net.IP

			if addr, ok := addrs[i].(*net.IPNet); ok {
				ip = addr.IP
			} else if addr, ok := addrs[i].(*net.IPAddr); ok {
				ip = addr.IP
			}

			if ip != nil {
				if IsPrivateIPAddress(ip) {
					l4g.Debug("Found private addr %v", ip)
					ret = append(ret, &net.UDPAddr{
						IP:   ip,
						Port: 0,
					})
				}
			}
		}
	} else {
		l4g.Warn(err)
	}
	return
}
Ejemplo n.º 29
0
func GetLocalIp() ([]string, error) {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		err = fmt.Errorf("get InterfaceAddrs error, err:%v", err)
		return nil, err
	}

	iplist := make([]string, 0)

	for _, a := range addrs {
		if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				iplist = append(iplist, ipnet.IP.String())
			}
		}
	}

	count := len(iplist)
	if count == 0 {
		err = fmt.Errorf("get ip count failure, count:%v", count)
		return nil, err
	}

	return iplist, nil
}
Ejemplo n.º 30
0
func heartbeat() {
	for {

		u, err := url.Parse(*couchbaseServer)
		c, err := net.Dial("tcp", u.Host)
		localAddr := ""
		if err == nil {
			localAddr = strings.Split(c.LocalAddr().String(), ":")[0]
			c.Close()
		}

		aboutMe := map[string]interface{}{
			"addr":     localAddr,
			"type":     "storage",
			"time":     time.Now().UTC(),
			"bindaddr": *bindAddr,
			"hash":     *hashType,
		}
		intfs, err := net.InterfaceAddrs()
		if err == nil {
			addrs := []string{}
			for _, intf := range intfs {
				addrs = append(addrs, intf.String())
			}
			aboutMe["interfaces"] = addrs
		}
		err = couchbase.Set("/"+serverIdentifier(), aboutMe)
		if err != nil {
			log.Printf("Failed to record a heartbeat: %v", err)
		}
		time.Sleep(5 * time.Second)
	}
}