Compare IP host/container

I would like to create a service that checks the host’s IP and compares it with the IP of a podman container.

If it is the same then stopped the container and if possible sent a notification for example with ntfy.

To compare I thought I would use on the host:
curl -sS https://ipinfo.io/json
and in the container:
podman exec -it <container_name> curl -sS https://ipinfo.io/json.

any idea how to implement this?

I’d like to respond with a different question: why?

This smells like something that should be approached the other way around, i.e., just don’t start containers with the same IP. Or do some networking/namespace voodoo that makes whatever you’re trying to solve here not a problem in the first place.

If you really want to do it, though, write a script that checks it once for all running containers, and then call it periodically with a systemd timer. That’s neither efficient nor does it prevent such containers existing for small intervals, so consider not doing this.

I’m also struggling to imagine a scenario in which the external IP addresses don’t match. Pretty sure you’d need a separate network device for each container to achieve that? Does podman support this? yes it does!

these containers are already with a different external IP address, they go through a VPN.

the idea is to periodically check with a systemd timer if the IPs are indeed different, in the event of a problem with the VPN or with the router which manages the VPN

Right, do you need to shut down the services in that case or would it be enough to cut their connection to the internet? If the latter is enough, you could instead set up firewall rules that block their traffic via anything except the firewall interface.

Since a polling service would not react instantly, you would still leak traffic over your non-VPN IP if you used a systemd timer, which might not be what you want.

1 Like

ultimately, I used an approach that suits me well, I share it for those interested.

it’s not perfect, there will always be a delay and IP leak time to detect.

  systemd.services.ipcheck = {
    serviceConfig = {
        Type = "oneshot";
    };
    script = ''
      HostIP=$(${pkgs.curl}/bin/curl -sS ipinfo.io/ip)
      ContainerIP=$(${pkgs.podman}/bin/podman exec -it <container_name> curl -sS ipinfo.io/ip)
      
      if [ "$HostIP" != "$ContainerIP" ] ; then 
        echo "vpn ok"
      else
        echo "vpn fail"
        systemctl stop podman-<container_name>.service
      fi
    '';
  };

  systemd.timers.ipcheck = {
    timerConfig = {
      Unit = "ipcheck.service";
      OnCalendar = "*:0/15";
    };
    wantedBy = [ "timers.target" ];
  };