2021-08-25 17:52:05 +00:00
|
|
|
package routing
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"errors"
|
|
|
|
|
"fmt"
|
|
|
|
|
"net"
|
2023-05-20 19:58:18 +00:00
|
|
|
"net/netip"
|
2022-09-14 02:18:10 +02:00
|
|
|
|
|
|
|
|
"github.com/qdm12/gluetun/internal/netlink"
|
2021-08-25 17:52:05 +00:00
|
|
|
)
|
|
|
|
|
|
2023-06-08 09:13:55 +00:00
|
|
|
func ipIsPrivate(ip netip.Addr) bool {
|
2021-08-25 17:52:05 +00:00
|
|
|
return ip.IsPrivate() || ip.IsLoopback() ||
|
|
|
|
|
ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast()
|
|
|
|
|
}
|
|
|
|
|
|
2024-10-11 19:20:48 +00:00
|
|
|
var errInterfaceIPNotFound = errors.New("IP address not found for interface")
|
2021-08-25 17:52:05 +00:00
|
|
|
|
2023-05-20 19:58:18 +00:00
|
|
|
func ipMatchesFamily(ip netip.Addr, family int) bool {
|
2023-05-29 06:44:58 +00:00
|
|
|
return (family == netlink.FamilyV4 && ip.Is4()) ||
|
|
|
|
|
(family == netlink.FamilyV6 && ip.Is6())
|
2022-09-14 02:18:10 +02:00
|
|
|
}
|
|
|
|
|
|
2024-07-30 22:00:26 +02:00
|
|
|
func (r *Routing) AssignedIP(interfaceName string, family int) (ip netip.Addr, err error) {
|
2021-08-25 17:52:05 +00:00
|
|
|
iface, err := net.InterfaceByName(interfaceName)
|
|
|
|
|
if err != nil {
|
2023-05-20 19:58:18 +00:00
|
|
|
return ip, fmt.Errorf("network interface %s not found: %w", interfaceName, err)
|
2021-08-25 17:52:05 +00:00
|
|
|
}
|
|
|
|
|
addresses, err := iface.Addrs()
|
|
|
|
|
if err != nil {
|
2023-05-20 19:58:18 +00:00
|
|
|
return ip, fmt.Errorf("listing interface %s addresses: %w", interfaceName, err)
|
2021-08-25 17:52:05 +00:00
|
|
|
}
|
|
|
|
|
for _, address := range addresses {
|
|
|
|
|
switch value := address.(type) {
|
|
|
|
|
case *net.IPAddr:
|
2023-05-20 19:58:18 +00:00
|
|
|
ip = netIPToNetipAddress(value.IP)
|
2021-08-25 17:52:05 +00:00
|
|
|
case *net.IPNet:
|
2023-05-20 19:58:18 +00:00
|
|
|
ip = netIPToNetipAddress(value.IP)
|
2023-04-27 13:41:05 +00:00
|
|
|
default:
|
|
|
|
|
continue
|
2021-08-25 17:52:05 +00:00
|
|
|
}
|
2023-04-27 13:41:05 +00:00
|
|
|
|
|
|
|
|
if !ipMatchesFamily(ip, family) {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
|
2023-05-22 08:03:52 +00:00
|
|
|
return ip, nil
|
2021-08-25 17:52:05 +00:00
|
|
|
}
|
2023-05-20 19:58:18 +00:00
|
|
|
return ip, fmt.Errorf("%w: interface %s in %d addresses",
|
2021-08-25 17:52:05 +00:00
|
|
|
errInterfaceIPNotFound, interfaceName, len(addresses))
|
|
|
|
|
}
|