OSDN Git Service

try to fix ban peer bug (#273)
[bytom/vapor.git] / p2p / external_ip.go
1 package p2p
2
3 import (
4         "net"
5 )
6
7 // ExternalIPv4 returns the first IPv4 available.
8 func ExternalIPv4() (string, error) {
9         ifaces, err := net.Interfaces()
10         if err != nil {
11                 return "", err
12         }
13
14         for _, iface := range ifaces {
15                 // interface down
16                 if iface.Flags&net.FlagUp == 0 {
17                         continue
18                 }
19                 // loopback interface
20                 if iface.Flags&net.FlagLoopback != 0 {
21                         continue
22                 }
23                 addrs, err := iface.Addrs()
24                 if err != nil {
25                         return "", err
26                 }
27
28                 for _, addr := range addrs {
29                         var ip net.IP
30                         switch v := addr.(type) {
31                         case *net.IPNet:
32                                 ip = v.IP
33                         case *net.IPAddr:
34                                 ip = v.IP
35                         }
36                         if ip == nil || ip.IsLoopback() {
37                                 continue
38                         }
39                         ip = ip.To4()
40                         if ip == nil {
41                                 continue // not an ipv4 address
42                         }
43                         return ip.String(), nil
44                 }
45         }
46         return "127.0.0.1", nil
47 }