bedrocktool/utils/net.go

47 lines
900 B
Go
Raw Normal View History

2022-09-04 14:26:32 +00:00
package utils
2023-04-01 22:22:50 +00:00
import (
"net"
2022-09-04 14:26:32 +00:00
2023-04-01 22:22:50 +00:00
"github.com/repeale/fp-go"
)
var privateIPNetworks = []net.IPNet{
2022-09-04 14:26:32 +00:00
{
IP: net.ParseIP("10.0.0.0"),
Mask: net.CIDRMask(8, 32),
},
{
IP: net.ParseIP("172.16.0.0"),
Mask: net.CIDRMask(12, 32),
},
{
IP: net.ParseIP("192.168.0.0"),
Mask: net.CIDRMask(16, 32),
},
}
2023-01-29 21:20:13 +00:00
// IPPrivate checks if ip is private
2022-09-04 14:26:32 +00:00
func IPPrivate(ip net.IP) bool {
2023-04-01 22:22:50 +00:00
return fp.Some(func(ipNet net.IPNet) bool {
return ipNet.Contains(ip)
})(privateIPNetworks)
2022-09-04 14:26:32 +00:00
}
// GetLocalIP returns the non loopback local IP of the host
func GetLocalIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
}
for _, address := range addrs {
// check the address type and if it is not a loopback the display it
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
}
}
}
return ""
}