From 64ce6949f23b308a432e83ec46c99ba67777ee1e Mon Sep 17 00:00:00 2001 From: Daniel J Walsh Date: Sat, 20 Nov 2021 09:00:22 -0500 Subject: [PATCH] Use hosts public ip address in rootless containers Add first non localhost ipv4 of all host interfaces as destination for host.contaners.internal for rootless containers. Fixes: https://github.com/containers/podman/issues/12000 Signed-off-by: Daniel J Walsh --- libpod/container_internal_linux.go | 23 ++++++++++++++++++----- test/system/500-networking.bats | 3 ++- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/libpod/container_internal_linux.go b/libpod/container_internal_linux.go index 9e6ae9f025..c2ec02e574 100644 --- a/libpod/container_internal_linux.go +++ b/libpod/container_internal_linux.go @@ -2154,11 +2154,24 @@ func (c *Container) getHosts() string { } } } else if c.config.NetMode.IsSlirp4netns() { - gatewayIP, err := GetSlirp4netnsGateway(c.slirp4netnsSubnet) - if err != nil { - logrus.Warn("Failed to determine gatewayIP: ", err.Error()) - } else { - hosts += fmt.Sprintf("%s host.containers.internal\n", gatewayIP.String()) + // getLocalIP returns the non loopback local IP of the host + getLocalIP := func() 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 "" + } + if ip := getLocalIP(); ip != "" { + hosts += fmt.Sprintf("%s\t%s\n", ip, "host.containers.internal") } } else { logrus.Debug("Network configuration does not support host.containers.internal address") diff --git a/test/system/500-networking.bats b/test/system/500-networking.bats index 4d36163d73..2b5ad44dc4 100644 --- a/test/system/500-networking.bats +++ b/test/system/500-networking.bats @@ -139,10 +139,11 @@ load helpers @test "podman run with slirp4ns assigns correct addresses to /etc/hosts" { CIDR="$(random_rfc1918_subnet)" + IP=$(hostname -I | cut -f 1 -d " ") local conname=con-$(random_string 10) run_podman run --rm --network slirp4netns:cidr="${CIDR}.0/24" \ --name $conname --hostname $conname $IMAGE cat /etc/hosts - is "$output" ".*${CIDR}.2 host.containers.internal" "host.containers.internal should be the cidr+2 address" + is "$output" ".*${IP} host.containers.internal" "host.containers.internal should be the cidr+2 address" is "$output" ".*${CIDR}.100 $conname $conname" "$conname should be the cidr+100 address" }