[英]How to use Golang to get my wifi ip address?
func getLocalIP() ([]string, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return nil, err
}
IPs := make([]string, 0)
for _, a := range addrs {
if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
if ipNet.IP.To4() != nil {
IPs = append(IPs, ipNet.IP.To4().String())
}
}
}
return IPs, nil
}
func TestGetLocalIP() {
addrs, _ := getLocalIP()
for _, a := range addrs {
fmt.Println(a)
}
}
我用過這個,但它給了我一個 ip 地址的列表。
我只想獲取我的 wifi 本地地址,該怎么做?
您需要至少知道以下兩條信息中的一條:
en0
,例如,但 YMMV)ifs, _ := net.Interfaces()
for _, ifi := range ifs {
if ifi.Name == "en0" { // Or whatever other filter you want
addrs, _ := ifi.Addresses()
for _, a := range addrs {
// Filter to get the one you want, typically unicast IP4
}
}
}
更簡單:
if, _ := net.InterfaceByName("en0")
addrs, _ := if.Addresses()
for _, a := range addrs {
// As before, filter for the address you want
}
// Loop over interfaces, get addrs, then loop over addresses and get IPs for those that have them
if ip.Mask(net.CIDRMask(16, 32)) == myNetworkAddress {
// The interface you got this IP from is probably your wifi interface
}
取決於具有特定名稱的接口通常不會是可移植的。 因此,雖然我的假設是您只是想讓它在您自己的工作站上運行,但如果這是為了需要在多個主機上運行的東西,您可能需要至少從匹配正確的網絡地址開始。 還有其他技巧 - 如果您知道例如您將在服務器場中運行,其中每個主機都有制造商 XXX 的 NIC,您可以查找 MAC 地址並查看它是否來自該制造商 - 您可以在這里試試這個。 您也可以使用其他過濾器,但這些過濾器將非常特定於您的個人用例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.