golang 获取本机真实IP

 1 package main
 2 
 3 import (
 4     "errors"
 5     "fmt"
 6     "net"
 7 )
 8 
 9 func externalIP() (net.IP, error) {
10     ifaces, err := net.Interfaces()
11     if err != nil {
12         return nil, err
13     }
14     for _, iface := range ifaces {
15         if iface.Flags&net.FlagUp == 0 {
16             continue // interface down
17         }
18         if iface.Flags&net.FlagLoopback != 0 {
19             continue // loopback interface
20         }
21         addrs, err := iface.Addrs()
22         if err != nil {
23             return nil, err
24         }
25         for _, addr := range addrs {
26             ip := getIpFromAddr(addr)
27             if ip == nil {
28                 continue
29             }
30             return ip, nil
31         }
32     }
33     return nil, errors.New("connected to the network?")
34 }
35 
36 func getIpFromAddr(addr net.Addr) net.IP {
37     var ip net.IP
38     switch v := addr.(type) {
39     case *net.IPNet:
40         ip = v.IP
41     case *net.IPAddr:
42         ip = v.IP
43     }
44     if ip == nil || ip.IsLoopback() {
45         return nil
46     }
47     ip = ip.To4()
48     if ip == nil {
49         return nil // not an ipv4 address
50     }
51 
52     return ip
53 }
54 
55 func main() {
56     ip, err := externalIP()
57     if err != nil {
58         fmt.Println(err)
59     }
60 
61     fmt.Println(ip.String())
62 }

 

posted @ 2019-08-05 11:23  追逐~~~  阅读(18883)  评论(0编辑  收藏  举报