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


Golang net.InterfaceAddrs函数代码示例

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


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

示例1: IvsOffLine

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..")
	}

}
开发者ID:limbo-cn,项目名称:GoTicker,代码行数:28,代码来源:alarmguard.go

示例2: main

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)

	}
}
开发者ID:torees,项目名称:Sanntid,代码行数:49,代码来源:phoenix.go

示例3: getFirstLocalIPAddr

// 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")
}
开发者ID:brutella,项目名称:hklifx,代码行数:28,代码来源:config.go

示例4: main

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)
	}
}
开发者ID:tslnc04,项目名称:world-server,代码行数:26,代码来源:main.go

示例5: interfaceURLs

// 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
}
开发者ID:safchain,项目名称:skydive,代码行数:32,代码来源:etcd.go

示例6: localhost

func (cm *connMetadata) localhost() net.Addr {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		panic(err)
	}
	return addrs[0]
}
开发者ID:vdice,项目名称:builder,代码行数:7,代码来源:server_test.go

示例7: TestCLIProxyProxyTCPSock

// 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)
}
开发者ID:docker,项目名称:docker,代码行数:31,代码来源:docker_cli_proxy_test.go

示例8: printInterfaces

// 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)
	}
}
开发者ID:edi-design,项目名称:kd-go,代码行数:29,代码来源:service.go

示例9: printAddressAndPort

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()

}
开发者ID:joncrlsn,项目名称:mypfs,代码行数:26,代码来源:main.go

示例10: printServerMsg

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)
		}
	}
}
开发者ID:nohitall,项目名称:minio,代码行数:29,代码来源:server-main.go

示例11: ComposeProfile

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
}
开发者ID:jaredwilkening,项目名称:AWE,代码行数:31,代码来源:heartbeater.go

示例12: calculateHostname

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
}
开发者ID:neocortical,项目名称:log5go,代码行数:31,代码来源:syslog.go

示例13: GetLocalIPs

// 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
}
开发者ID:Charlesdong,项目名称:godropbox,代码行数:36,代码来源:ip.go

示例14: defaultWorkId

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
}
开发者ID:Ray-GuanhuiLiang,项目名称:GoGuidGenerator,代码行数:35,代码来源:guid.go

示例15: GetExternalIP

// 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]
	}
}
开发者ID:robmurtha,项目名称:goq,代码行数:37,代码来源:ipaddr.go


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