Golang获取随机端口和本机ip地址

时间:2022-05-04
本文章向大家介绍Golang获取随机端口和本机ip地址,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
l, _ := net.Listen("tcp", ":0") // listen on localhost
	port := l.Addr().(*net.TCPAddr).Port
	ip := l.Addr().(*net.TCPAddr).IP
	fmt.Println(ip, port)

	ifaces, _ := net.Interfaces()
	// handle err
	for _, i := range ifaces {

		addrs, _ := i.Addrs()
		// handle err
		for _, addr := range addrs {			switch v := addr.(type) {
			case *net.IPAddr:
				fmt.Println(v.IP)
			}

		}
	}