go中如何獲取本機(jī)ip地址
更新時間:2023年09月18日 09:06:12 作者:L小象
這篇文章主要介紹了go中如何獲取本機(jī)ip地址問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
go獲取本機(jī)ip地址
獲取本機(jī)ip的方法:
//獲取ip func externalIP() (net.IP, error) { ifaces, err := net.Interfaces() if err != nil { return nil, err } for _, iface := range ifaces { if iface.Flags&net.FlagUp == 0 { continue // interface down } if iface.Flags&net.FlagLoopback != 0 { continue // loopback interface } addrs, err := iface.Addrs() if err != nil { return nil, err } for _, addr := range addrs { ip := getIpFromAddr(addr) if ip == nil { continue } return ip, nil } } return nil, errors.New("connected to the network?") } //獲取ip func getIpFromAddr(addr net.Addr) net.IP { 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() { return nil } ip = ip.To4() if ip == nil { return nil // not an ipv4 address } return ip }
調(diào)用:
func main() { ip, err := externalIP() if err != nil { fmt.Println(err) } fmt.Printf(ip.String()) }
結(jié)果:
Golang獲取本機(jī)的Mac 和ip地址
獲取本機(jī)的Mac 和ip地址
1.獲取本機(jī)的MAC地址
代碼如下(示例):
func GetLocalMac() (mac string) { // 獲取本機(jī)的MAC地址 interfaces, err := net.Interfaces() if err != nil { panic("Poor soul, here is what you got: " + err.Error()) } for _, inter := range interfaces { fmt.Println(inter.Name) mac := inter.HardwareAddr //獲取本機(jī)MAC地址 fmt.Println("MAC ===== ", mac) } fmt.Println("MAC = ", mac) return mac }
2.獲取本機(jī)ip地址
代碼如下(示例):
//獲取本機(jī)ip地址 func GetIps() (ips []string) { interfaceAddr, err := net.InterfaceAddrs() if err != nil { fmt.Printf("fail to get net interfaces ipAddress: %v\n", err) return ips } for _, address := range interfaceAddr { ipNet, isVailIpNet := address.(*net.IPNet) if isVailIpNet && !ipNet.IP.IsLoopback() { if ipNet.IP.To4() != nil { ips = append(ips, ipNet.IP.String()) } } } fmt.Println("ips = ", ips) return ips }
總結(jié)
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Golang 語言控制并發(fā) Goroutine的方法
本文我們介紹了不同場景中分別適合哪種控制并發(fā) goroutine 的方式,其中,channel 適合控制少量 并發(fā) goroutine,WaitGroup 適合控制一組并發(fā) goroutine,而 context 適合控制多級并發(fā) goroutine,感興趣的朋友跟隨小編一起看看吧2021-06-06Golang實(shí)現(xiàn)圖片上傳功能的示例代碼
這篇文章主要和大家分享一下如何利用Golang實(shí)現(xiàn)圖片上傳功能,文中的實(shí)現(xiàn)步驟講解詳細(xì),對我們學(xué)習(xí)有一定的參考價值,需要的可以參考一下2022-05-05Go net/http/pprof分析內(nèi)存泄露及解決過程
這篇文章主要介紹了Go net/http/pprof分析內(nèi)存泄露及解決過程,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-04-04