在 Golang 中,使用 net 包可以很方便地獲取到本機IP地址。
借助 net.InterfaceAddrs 方法
簡單示例代碼如下:文章來源:http://www.zghlxwxcb.cn/news/detail-605862.html
package main
import (
"fmt"
"net"
)
func main() {
addrList, err := net.InterfaceAddrs()
if err != nil {
panic(err)
}
for _, address := range addrList {
if ipNet, ok := address.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
if ipNet.IP.To4() != nil {
fmt.Println(ipNet.IP.String())
}
}
}
}
借助?net.Dial 方法
使用 udp 不需要關(guān)注是否送達(dá),只需要對應(yīng)的 ip 和 port 正確,即可獲取到 IP 地址。簡單示例代碼如下:文章來源地址http://www.zghlxwxcb.cn/news/detail-605862.html
package main
import (
"fmt"
"net"
"strings"
)
func main() {
conn, err := net.Dial("udp", "8.8.8.8:53")
if err != nil {
panic(err)
}
addr := conn.LocalAddr().(*net.UDPAddr)
ip := strings.Split(addr.String(), ":")[0]
fmt.Println(ip)
}
到了這里,關(guān)于Golang 獲取本地 IP 地址方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!