localIp returns a local IP from one of the local interfaces.
()
| 49 | |
| 50 | // localIp returns a local IP from one of the local interfaces. |
| 51 | func localIP() (net.IP, error) { |
| 52 | tt, err := net.Interfaces() |
| 53 | if err != nil { |
| 54 | return nil, err |
| 55 | } |
| 56 | |
| 57 | for _, t := range tt { |
| 58 | aa, err := t.Addrs() |
| 59 | if err != nil { |
| 60 | return nil, err |
| 61 | } |
| 62 | for _, a := range aa { |
| 63 | ipnet, ok := a.(*net.IPNet) |
| 64 | if !ok { |
| 65 | continue |
| 66 | } |
| 67 | v4 := ipnet.IP.To4() |
| 68 | |
| 69 | if v4 == nil || v4[0] == 127 { // loopback address |
| 70 | continue |
| 71 | } |
| 72 | return v4, nil |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | return nil, errors.New("cannot find local IP address") |
| 77 | } |
| 78 | |
| 79 | // publicIP returns an IP that is supposed to be Public. |
| 80 | func publicIP() (net.IP, error) { |