| 245 | } |
| 246 | |
| 247 | func interfaceIP(intf *net.Interface) (net.IP, error) { |
| 248 | addrs, err := intf.Addrs() |
| 249 | if err != nil { |
| 250 | return nil, err |
| 251 | } |
| 252 | |
| 253 | // Try to find an IPv4 address to use, in the following order: |
| 254 | // global unicast (includes rfc1918), link-local unicast, |
| 255 | // loopback. |
| 256 | fs := [](func(net.IP) bool){ |
| 257 | net.IP.IsGlobalUnicast, |
| 258 | net.IP.IsLinkLocalUnicast, |
| 259 | net.IP.IsLoopback, |
| 260 | } |
| 261 | for _, f := range fs { |
| 262 | for _, a := range addrs { |
| 263 | ipaddr, ok := a.(*net.IPNet) |
| 264 | if !ok { |
| 265 | continue |
| 266 | } |
| 267 | ip := ipaddr.IP.To4() |
| 268 | if ip == nil { |
| 269 | continue |
| 270 | } |
| 271 | if f(ip) { |
| 272 | return ip, nil |
| 273 | } |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | return nil, errors.New("no usable unicast address configured on interface") |
| 278 | } |