arcast/pkg/server/network.go

61 lines
1.1 KiB
Go
Raw Permalink Normal View History

2023-12-13 20:07:22 +01:00
package server
import (
"net"
"github.com/pkg/errors"
"github.com/wlynxg/anet"
)
var (
_, lanA, _ = net.ParseCIDR("10.0.0.0/8")
_, lanB, _ = net.ParseCIDR("172.16.0.0/12")
_, lanC, _ = net.ParseCIDR("192.168.0.0/16")
)
func getLANIPv4Addrs() ([]string, error) {
ips := make([]string, 0)
addrs, err := anet.InterfaceAddrs()
if err != nil {
return nil, errors.WithStack(err)
}
for _, address := range addrs {
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
ipv4 := ipnet.IP.To4()
if ipv4 == nil {
continue
}
isLAN := lanA.Contains(ipv4) || lanB.Contains(ipv4) || lanC.Contains(ipv4)
if !isLAN {
continue
}
ips = append(ips, ipv4.String())
}
}
return ips, nil
}
func FindPreferredLocalAddress(ips ...net.IP) (string, error) {
localAddrs, err := anet.InterfaceAddrs()
if err != nil {
return "", errors.WithStack(err)
}
for _, addr := range localAddrs {
if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
for _, ip := range ips {
if ipnet.Contains(ip) {
return ip.String(), nil
}
}
}
}
return ips[0].String(), nil
}