forked from influxdata/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
97 lines (84 loc) · 1.93 KB
/
connection.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package ipmi_sensor
import (
"fmt"
"net"
"strconv"
"strings"
)
// Connection properties for a Client
type Connection struct {
Hostname string
Username string
Password string
Port int
Interface string
Privilege string
HexKey string
}
func NewConnection(server, privilege, hexKey string) *Connection {
conn := &Connection{
Privilege: privilege,
HexKey: hexKey,
}
inx1 := strings.LastIndex(server, "@")
inx2 := strings.Index(server, "(")
connstr := server
if inx1 > 0 {
security := server[0:inx1]
connstr = server[inx1+1:]
up := strings.SplitN(security, ":", 2)
conn.Username = up[0]
conn.Password = up[1]
}
if inx2 > 0 {
inx2 = strings.Index(connstr, "(")
inx3 := strings.Index(connstr, ")")
conn.Interface = connstr[0:inx2]
conn.Hostname = connstr[inx2+1 : inx3]
}
return conn
}
func (t *Connection) options() []string {
intf := t.Interface
if intf == "" {
intf = "lan"
}
options := []string{
"-H", t.Hostname,
"-U", t.Username,
"-P", t.Password,
"-I", intf,
}
if t.HexKey != "" {
options = append(options, "-y", t.HexKey)
}
if t.Port != 0 {
options = append(options, "-p", strconv.Itoa(t.Port))
}
if t.Privilege != "" {
options = append(options, "-L", t.Privilege)
}
return options
}
// RemoteIP returns the remote (bmc) IP address of the Connection
func (c *Connection) RemoteIP() string {
if net.ParseIP(c.Hostname) == nil {
addrs, err := net.LookupHost(c.Hostname)
if err != nil && len(addrs) > 0 {
return addrs[0]
}
}
return c.Hostname
}
// LocalIP returns the local (client) IP address of the Connection
func (c *Connection) LocalIP() string {
conn, err := net.Dial("udp", fmt.Sprintf("%s:%d", c.Hostname, c.Port))
if err != nil {
// don't bother returning an error, since this value will never
// make it to the bmc if we can't connect to it.
return c.Hostname
}
_ = conn.Close()
host, _, _ := net.SplitHostPort(conn.LocalAddr().String())
return host
}