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