go获取内网ip与外网ip

1,go获取内网ip与外网ip

package ipUtil

import (
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
)

func GetIp(local bool) string {
	var ip = ""
	if local {
		ip = nip()
	} else {
		ip = wip()
	}
	fmt.Println("GetIp=" + ip)
	return ip
}
func main() {
	GetIp(false)
	GetIp(true)
}

/*
*
获取内网ip
*/
func nip() string {
	ifaces, err := net.Interfaces()
	if err != nil {
		fmt.Println(err)
		return ""
	}

	for _, iface := range ifaces {
		addrs, err := iface.Addrs()
		if err != nil {
			fmt.Println(err)
			continue
		}
		for _, addr := range addrs {
			ipnet, ok := addr.(*net.IPNet)
			if ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil {
				ip := ipnet.IP
				fmt.Println(ip.String())
				return ip.String()
			}
		}
	}
	return ""
}

/*
*
获取外网ip
*/
func wip() string {
	resp, err := http.Get("https://api.ipify.org?format=text")
	if err != nil {
		fmt.Println(err)
		return ""
	}
	defer resp.Body.Close()

	ip, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return ""
	}

	fmt.Println(string(ip))
	return string(ip)
}

你可能感兴趣的:(GoLang,golang,tcp/ip)