-
Notifications
You must be signed in to change notification settings - Fork 0
/
net.go
277 lines (231 loc) · 5.41 KB
/
net.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package netutil
import (
"bytes"
"encoding/json"
"errors"
"io"
"mime/multipart"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"runtime"
"strings"
"time"
"github.com/khaosles/giz/fileutil"
)
/*
@File: net.go
@Author: khaosles
@Time: 2023/8/13 12:56
@Desc:
*/
// GetInternalIp return internal ipv4.
func GetInternalIp() string {
addr, err := net.InterfaceAddrs()
if err != nil {
panic(err.Error())
}
for _, a := range addr {
if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
if ipNet.IP.To4() != nil {
return ipNet.IP.String()
}
}
}
return ""
}
// GetRequestPublicIp return the requested public ip.
func GetRequestPublicIp(req *http.Request) string {
var ip string
for _, ip = range strings.Split(req.Header.Get("X-Forwarded-For"), ",") {
if ip = strings.TrimSpace(ip); ip != "" && !IsInternalIP(net.ParseIP(ip)) {
return ip
}
}
if ip = strings.TrimSpace(req.Header.Get("X-Real-Ip")); ip != "" && !IsInternalIP(net.ParseIP(ip)) {
return ip
}
if ip, _, _ = net.SplitHostPort(req.RemoteAddr); !IsInternalIP(net.ParseIP(ip)) {
return ip
}
return ip
}
// GetPublicIpInfo return public ip information
// return the PublicIpInfo struct.
func GetPublicIpInfo() (*PublicIpInfo, error) {
resp, err := http.Get("http://ip-api.com/json/")
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var ip PublicIpInfo
err = json.Unmarshal(body, &ip)
if err != nil {
return nil, err
}
return &ip, nil
}
// GetIps return all ipv4 of system.
func GetIps() []string {
var ips []string
addrs, err := net.InterfaceAddrs()
if err != nil {
return ips
}
for _, addr := range addrs {
ipNet, isValid := addr.(*net.IPNet)
if isValid && !ipNet.IP.IsLoopback() {
if ipNet.IP.To4() != nil {
ips = append(ips, ipNet.IP.String())
}
}
}
return ips
}
// GetMacAddrs get mac address.
func GetMacAddrs() []string {
var macAddrs []string
nets, err := net.Interfaces()
if err != nil {
return macAddrs
}
for _, net := range nets {
macAddr := net.HardwareAddr.String()
if len(macAddr) == 0 {
continue
}
macAddrs = append(macAddrs, macAddr)
}
return macAddrs
}
// PublicIpInfo public ip info: country, region, isp, city, lat, lon, ip
type PublicIpInfo struct {
Status string `json:"status"`
Country string `json:"country"`
CountryCode string `json:"countryCode"`
Region string `json:"region"`
RegionName string `json:"regionName"`
City string `json:"city"`
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
Isp string `json:"isp"`
Org string `json:"org"`
As string `json:"as"`
Ip string `json:"query"`
}
// IsPublicIP verify a ip is public or not.
func IsPublicIP(IP net.IP) bool {
if IP.IsLoopback() || IP.IsLinkLocalMulticast() || IP.IsLinkLocalUnicast() {
return false
}
if ip4 := IP.To4(); ip4 != nil {
switch {
case ip4[0] == 10:
return false
case ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31:
return false
case ip4[0] == 192 && ip4[1] == 168:
return false
default:
return true
}
}
return false
}
// IsInternalIP verify an ip is intranet or not.
func IsInternalIP(IP net.IP) bool {
if IP.IsLoopback() {
return true
}
if ip4 := IP.To4(); ip4 != nil {
return ip4[0] == 10 ||
(ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31) ||
(ip4[0] == 169 && ip4[1] == 254) ||
(ip4[0] == 192 && ip4[1] == 168)
}
return false
}
// EncodeUrl encode url.
func EncodeUrl(urlStr string) (string, error) {
URL, err := url.Parse(urlStr)
if err != nil {
return "", err
}
URL.RawQuery = URL.Query().Encode()
return URL.String(), nil
}
// UploadFile will upload the file to a server.
func UploadFile(filepath string, server string) (bool, error) {
if !fileutil.Exist(filepath) {
return false, errors.New("file not exist")
}
fileInfo, err := os.Stat(filepath)
if err != nil {
return false, err
}
bodyBuffer := &bytes.Buffer{}
writer := multipart.NewWriter(bodyBuffer)
formFile, err := writer.CreateFormFile("uploadfile", fileInfo.Name())
if err != nil {
return false, err
}
srcFile, err := os.Open(filepath)
if err != nil {
return false, err
}
defer srcFile.Close()
_, err = io.Copy(formFile, srcFile)
if err != nil {
return false, err
}
contentType := writer.FormDataContentType()
writer.Close()
_, err = http.Post(server, contentType, bodyBuffer)
if err != nil {
return false, err
}
return true, nil
}
// DownloadFile will download the file exist in url to a local file.
func DownloadFile(filepath string, url string) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
return err
}
// IsPingConnected checks if can ping specified host or not.
func IsPingConnected(host string) bool {
cmd := exec.Command("ping", host, "-c", "4", "-W", "6")
if runtime.GOOS == "windows" {
cmd = exec.Command("ping", host, "-n", "4", "-w", "6")
}
err := cmd.Run()
if err != nil {
return false
}
return true
}
// IsTelnetConnected checks if can telnet specified host or not.
func IsTelnetConnected(host string, port string) bool {
adder := host + ":" + port
conn, err := net.DialTimeout("tcp", adder, 5*time.Second)
if err != nil {
return false
}
defer conn.Close()
return true
}