Fix routing between containers on same host

This commit is contained in:
Scott Yeager 2025-06-20 20:10:00 -07:00
parent 0618b41ae2
commit 4012686925

28
main.go
View File

@ -150,13 +150,13 @@ func getMyceliumIP(interfaceName string) (net.IP, error) {
func generateContainerIP(myceliumPrefix net.IP, containerID string) net.IP { func generateContainerIP(myceliumPrefix net.IP, containerID string) net.IP {
// Generate a unique container IP within the /64 prefix using container ID hash // Generate a unique container IP within the /64 prefix using container ID hash
hash := sha256.Sum256([]byte(containerID)) hash := sha256.Sum256([]byte(containerID))
containerIP := make(net.IP, len(myceliumPrefix)) containerIP := make(net.IP, len(myceliumPrefix))
copy(containerIP, myceliumPrefix) copy(containerIP, myceliumPrefix)
// Use first 8 bytes of hash for the host part (last 64 bits) // Use first 8 bytes of hash for the host part (last 64 bits)
copy(containerIP[8:], hash[:8]) copy(containerIP[8:], hash[:8])
return containerIP return containerIP
} }
@ -259,8 +259,28 @@ func configureContainerInterface(containerNS netns.NsHandle, ifName string, cont
} }
if hostLLAddr != nil { if hostLLAddr != nil {
// Add route to Mycelium network via host veth // First remove any existing route to our /64
myceliumPrefix := &net.IPNet{
IP: containerIP.Mask(net.CIDRMask(64, 128)),
Mask: net.CIDRMask(64, 128),
}
existingRoute := &netlink.Route{
Dst: myceliumPrefix,
}
netlink.RouteDel(existingRoute)
// Add route to our /64 via host veth
route := &netlink.Route{ route := &netlink.Route{
Dst: myceliumPrefix,
Gw: hostLLAddr,
LinkIndex: link.Attrs().Index,
}
if err := netlink.RouteAdd(route); err != nil {
return err
}
// Add route to Mycelium network via host veth
route = &netlink.Route{
Dst: &net.IPNet{ Dst: &net.IPNet{
IP: net.ParseIP("400::"), IP: net.ParseIP("400::"),
Mask: net.CIDRMask(7, 128), Mask: net.CIDRMask(7, 128),