blob: c37c4efeba78d55988b5c3230c28aea2d3b17708 [file] [log] [blame]
Stephane Barbarie35595062018-02-08 08:34:39 -05001package common
2
3import (
4 "github.com/google/gopacket"
5 "github.com/google/gopacket/layers"
6 "github.com/sirupsen/logrus"
7 "net"
8)
9
10func GetInterfaceIP(ifName string) string {
11 var err error
12 var netIf *net.Interface
13 var netAddrs []net.Addr
14 var netIp net.IP
15 var ipAddr string
16
17 if netIf, err = net.InterfaceByName(ifName); err == nil {
18 if netAddrs, err = netIf.Addrs(); err == nil {
19 for _, addr := range netAddrs {
20 Logger().WithFields(logrus.Fields{
21 "type": addr.Network(),
22 }).Debug("Address network type")
23 switch v := addr.(type) {
24 case *net.IPNet:
25 netIp = v.IP
26 case *net.IPAddr:
27 netIp = v.IP
28 }
29 if netIp == nil || netIp.IsLoopback() {
30 continue
31 }
32 netIp = netIp.To4()
33 if netIp == nil {
34 continue // not an ipv4 address
35 }
36 ipAddr = netIp.String()
37 break
38 }
39 }
40 }
41
42 return ipAddr
43}
44func GetHostIP(hostName string) string {
45 var err error
46 var ipAddrs []string
47 var ipAddr string
48
49 if ipAddrs, err = net.LookupHost(hostName); err == nil {
50 for _, ip := range ipAddrs {
51 if addr := net.ParseIP(ip); err == nil {
52 Logger().WithFields(logrus.Fields{
53 "ip": addr,
54 }).Debug("Host address")
55 if addr == nil /*|| addr.IsLoopback()*/ {
56 continue
57 }
58 ipAddr = ip
59 break
60 }
61 }
62 }
63
64 return ipAddr
65}
66func GetMacAddress(ifName string) net.HardwareAddr {
67 var err error
68 var netIf *net.Interface
69 var hwAddr net.HardwareAddr
70
71 if netIf, err = net.InterfaceByName(ifName); err == nil {
72 hwAddr = netIf.HardwareAddr
73 }
74
75 return hwAddr
76}
77
78func GetEthernetLayer(frame gopacket.Packet) *layers.Ethernet {
79 eth := &layers.Ethernet{}
80 if ethLayer := frame.Layer(layers.LayerTypeEthernet); ethLayer != nil {
81 eth, _ = ethLayer.(*layers.Ethernet)
82 }
83 return eth
84}
85func GetDot1QLayer(frame gopacket.Packet) *layers.Dot1Q {
86 var dot1q *layers.Dot1Q
87 //dot1q := &layers.Dot1Q{}
88 if dot1qLayer := frame.Layer(layers.LayerTypeDot1Q); dot1qLayer != nil {
89 dot1q, _ = dot1qLayer.(*layers.Dot1Q)
90 }
91 return dot1q
92}
93
94func GetIpLayer(frame gopacket.Packet) *layers.IPv4 {
95 ip := &layers.IPv4{}
96 if ipLayer := frame.Layer(layers.LayerTypeIPv4); ipLayer != nil {
97 ip, _ = ipLayer.(*layers.IPv4)
98 }
99 return ip
100}
101func GetUdpLayer(frame gopacket.Packet) *layers.UDP {
102 udp := &layers.UDP{}
103 if udpLayer := frame.Layer(layers.LayerTypeUDP); udpLayer != nil {
104 udp, _ = udpLayer.(*layers.UDP)
105 }
106 return udp
107}