-
Notifications
You must be signed in to change notification settings - Fork 0
/
commonnet.go
215 lines (159 loc) · 5.61 KB
/
commonnet.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package common
import (
"bytes"
"crypto/tls"
"errors"
"io"
"io/ioutil"
"net"
"net/http"
"strings"
"time"
upnp "github.com/NebulousLabs/go-upnp"
)
var (
// ExtIPProviders - preset macro defining list of available external IP checking services
ExtIPProviders = []string{"http://checkip.amazonaws.com/", "http://icanhazip.com/", "http://www.trackip.net/ip", "http://bot.whatismyipaddress.com/", "https://ipecho.net/plain", "http://myexternalip.com/raw"}
)
/* BEGIN EXPORTED METHODS */
// SendBytes - attempt to send specified bytes to given address
func SendBytes(b []byte, address string) error {
if strings.Count(address, ":") > 1 { // Check IPv6
address = "[" + address[:strings.LastIndex(address, ":")] + "]" + address[strings.LastIndex(address, ":"):] // Set address
}
connection, err := tls.Dial("tcp", address, GeneralTLSConfig) // Connect to given address
if err != nil { // Check for errors
return err // Return found error
}
_, err = connection.Write(b) // Write data to connection
if err != nil { // Check for errors
return err // Return found errors
}
err = connection.Close() // Close connection
if err != nil { // Check for errors
return err // Return found error
}
return nil // No error occurred, return nil
}
// ReadConnectionWaitAsyncNoTLS - attempt to read from connection in an asynchronous fashion, after waiting for peer to write
func ReadConnectionWaitAsyncNoTLS(conn net.Conn) ([]byte, error) {
data := make(chan []byte) // Init buffer
err := make(chan error) // Init error buffer
conn.SetReadDeadline(time.Now().Add(2 * time.Second)) // Set read deadline
go func(data chan []byte, err chan error) {
reads := 0 // Init reads buffer
for {
reads++ // Increment read
var buffer bytes.Buffer // Init buffer
readData, readErr := io.Copy(&buffer, conn) // Read connection
if readErr != nil && readErr != io.EOF && reads > 3 { // Check for errors
err <- readErr // Write read error
} else if readData == 0 { // Check for nil readData
continue // Continue
}
data <- buffer.Bytes() // Write read data
}
}(data, err)
ticker := time.Tick(3 * time.Second) // Init ticker
for { // Continuously read from connection
select {
case readData := <-data: // Read data from connection
return readData, nil // Return read data
case readErr := <-err: // Error on read
return []byte{}, readErr // Return error
case <-ticker: // Timed out
return []byte{}, errors.New("timed out") // Return timed out error
}
}
}
/*
BEGIN IP ADDR METHODS
*/
// GetExtIPAddrWithUPnP - retrieve the external IP address of the current machine via upnp
func GetExtIPAddrWithUPnP() (string, error) {
// connect to router
d, err := upnp.Discover()
if err != nil { // Check for errors
return "", err // return error
}
// discover external IP
ip, err := d.ExternalIP()
if err != nil { // Check for errors
return "", err // return error
}
return ip, nil
}
// GetExtIPAddrWithoutUPnP - retrieve the external IP address of the current machine w/o upnp
func GetExtIPAddrWithoutUPnP() (string, error) {
if len(ExtIPProviders) == 0 { // Check no providers
return "localhost", nil // Return localhost
}
addresses := []string{} // Init address buffer
finished := make(chan bool) // Init finished
for _, provider := range ExtIPProviders { // Iterate through providers
go getIPFromProviderAsync(provider, &addresses, finished) // Fetch IP
}
<-finished // Wait until finished
close(finished) // Close channel
return getNonNilInStringSlice(addresses) // Return valid address
}
// Connected - check if connected to internet
func Connected() (connected bool) {
resp, err := http.Get("http://clients3.google.com/generate_204") // Perform request
if err != nil { // Check for errors
return false // Return result
}
_, err = ioutil.ReadAll(resp.Body) // Read response
if err != nil { // Check for errors
return false // Return result
}
resp.Body.Close() // Close
return true // Return connected
}
/*
END IP ADDR METHODS
*/
/* END EXPORTED METHODS */
/* BEGIN INTERNAL METHODS */
// getIPFromProvider - get IP address from given IP provider
func getIPFromProvider(provider string) (string, error) {
resp, err := http.Get(provider) // Attempt to check IP via provider
if err != nil { // Check for errors
return "", err // Return error
}
defer resp.Body.Close() // Close connection
ip, err := ioutil.ReadAll(resp.Body) // Read address
if err != nil { // Check for errors
return "", err // Return error
}
stringVal := string(ip[:]) // Fetch string value
return strings.TrimSpace(stringVal), nil // Return ip
}
// getIPFromProviderAsync - asynchronously get IP address from given IP provider
func getIPFromProviderAsync(provider string, buffer *[]string, finished chan bool) {
if Connected() { // Check connected to internet
if len(*buffer) == 0 { // Check IP not already determined
resp, err := http.Get(provider) // Attempt to check IP via provider
if err != nil { // Check for errors
if len(*buffer) == 0 { // Double check IP not already determined
*buffer = append(*buffer, "") // Set IP
finished <- true // Set finished
}
} else {
defer resp.Body.Close() // Close connection
ip, _ := ioutil.ReadAll(resp.Body) // Read address
stringVal := string(ip[:]) // Fetch string value
if len(*buffer) == 0 { // Double check IP not already determined
*buffer = append(*buffer, strings.TrimSpace(stringVal)) // Set ip
finished <- true // Set finished
}
}
}
} else {
if len(*buffer) == 0 {
*buffer = append(*buffer, "localhost") // Set localhost
finished <- true // Set finished
}
}
}
/* END INTERNAL METHODS */