mirror of
https://github.com/Control-D-Inc/ctrld.git
synced 2026-08-10 13:20:33 +02:00
internal/clientinfo: ensure RFC1918 address is chosen over others
This commit is contained in:
@@ -8,6 +8,7 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"os"
|
"os"
|
||||||
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
@@ -138,20 +139,33 @@ func (d *dhcp) lookupIPByHostname(name string, v6 bool) string {
|
|||||||
if d == nil {
|
if d == nil {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
var ip string
|
var (
|
||||||
|
rfc1918Addrs []netip.Addr
|
||||||
|
others []netip.Addr
|
||||||
|
)
|
||||||
d.ip2name.Range(func(key, value any) bool {
|
d.ip2name.Range(func(key, value any) bool {
|
||||||
if value == name {
|
if value != name {
|
||||||
if addr, err := netip.ParseAddr(key.(string)); err == nil && addr.Is6() == v6 {
|
return true
|
||||||
ip = addr.String()
|
}
|
||||||
if addr.IsLoopback() { // Continue searching if this is loopback address.
|
if addr, err := netip.ParseAddr(key.(string)); err == nil && addr.Is6() == v6 {
|
||||||
return true
|
if addr.IsPrivate() {
|
||||||
}
|
rfc1918Addrs = append(rfc1918Addrs, addr)
|
||||||
return false
|
} else {
|
||||||
|
others = append(others, addr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
return ip
|
result := [][]netip.Addr{rfc1918Addrs, others}
|
||||||
|
for _, addrs := range result {
|
||||||
|
if len(addrs) > 0 {
|
||||||
|
sort.Slice(addrs, func(i, j int) bool {
|
||||||
|
return addrs[i].Less(addrs[j])
|
||||||
|
})
|
||||||
|
return addrs[0].String()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddLeaseFile adds given lease file for reading/watching clients info.
|
// AddLeaseFile adds given lease file for reading/watching clients info.
|
||||||
|
|||||||
@@ -86,3 +86,15 @@ lease 192.168.1.2 {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Test_dhcp_lookupIPByHostname(t *testing.T) {
|
||||||
|
d := &dhcp{}
|
||||||
|
want := "192.168.1.123"
|
||||||
|
d.ip2name.Store(want, "foo")
|
||||||
|
d.ip2name.Store("127.0.0.1", "foo")
|
||||||
|
d.ip2name.Store("169.254.123.123", "foo")
|
||||||
|
|
||||||
|
if got := d.lookupIPByHostname("foo", false); got != want {
|
||||||
|
t.Fatalf("unexpected result, want: %s, got: %s", want, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user