-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsource.go
50 lines (45 loc) · 1.05 KB
/
source.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main
import (
"net"
"os"
"strings"
)
type Source struct {
Hostname string
IPs []*net.IP
}
func NewSource() *Source {
hostname, err := os.Hostname()
if err != nil {
hostname = "localhost"
}
s := Source{
Hostname: hostname}
return &s
}
func (s *Source) String() string {
IPs := []string{}
for _, ip := range s.IPs {
IPs = append(IPs, ip.String())
}
return "[" + s.Hostname + "][" + strings.Join(IPs, ",") + "]"
}
// Returns a list of non-loopback IP addresses for the local device. These
// represent the source of traffic generated by this tool.
func GetLocalIPs() *Source {
source := NewSource()
addresses, err := net.InterfaceAddrs()
if err == nil {
for _, address := range addresses {
// ignore loopback interfaces and IPv6 altogether
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil {
source.IPs = append(source.IPs, &ipnet.IP)
}
}
}
if len(source.IPs) == 0 {
localhost := net.ParseIP("127.0.0.1")
source.IPs = append(source.IPs, &localhost)
}
return source
}