-
Notifications
You must be signed in to change notification settings - Fork 652
/
Copy pathip.go
63 lines (55 loc) · 1.3 KB
/
ip.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
package network
import (
"net"
"github.com/yaoapp/gou"
"github.com/yaoapp/kun/exception"
)
// IP 读取IP地址
func IP() map[string]string {
res := map[string]string{}
ifaces, err := net.Interfaces()
if err != nil {
exception.New("读取网卡失败 %s", 500, err.Error()).Throw()
}
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
exception.New("读取IP地址失败 %s", 500, err.Error()).Throw()
}
// handle err
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
res[i.Name] = ip.String()
}
}
return res
}
// ProcessIP xiang.network.IP IP地址
func ProcessIP(process *gou.Process) interface{} {
return IP()
}
// FreePort xiang.network.FreePort 获取可用端口
func FreePort() int {
addr, err := net.ResolveTCPAddr("tcp", ":0")
if err != nil {
exception.New("获取可用端口失败 %s", 500, err.Error()).Throw()
return 0
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
exception.New("获取可用端口失败 %s", 500, err.Error()).Throw()
return 0
}
defer l.Close()
return l.Addr().(*net.TCPAddr).Port
}
// ProcessFreePort xiang.network.FreePort 获取可用端口
func ProcessFreePort(process *gou.Process) interface{} {
return FreePort()
}