Home > Enterprise >  How to use Golang to get my wifi ip address?
How to use Golang to get my wifi ip address?

Time:01-29

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)
    }
}


I used this,but it give me a list of ip address.

I just want to get my wifi local address,how to do that?

CodePudding user response:

You need to know at least one of two pieces of information going in:

  1. the name of the correct interface (typically en0 on a Mac, e.g., but YMMV)
  2. the address for your wireless network, including the length of the mask - something like 192.168.0.0/16 or 192.168.0.0/24 is pretty common, but you'll have to figure this out ahead of time.

If you only know the interface name:

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
    }
  }
}

Still simpler:

if, _ := net.InterfaceByName("en0")
addrs, _ := if.Addresses()
for _, a := range addrs {
  // As before, filter for the address you want
}

If you know the network address for your wireless network

// 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
}
  • Related