LibVirt offers hooks which are triggered on VM actions like Start, Stop, ... It is possible to use these hooks to add/remove iptables rules (like port forwarding) which are specific to a VM. You can get more information about these hooks on the LibVirt documentation.

Example: port forwarding

Sometimes, we want to automatically update iptables rules when a VM's state changes. We use these hooks to forward specific ports when a specific VM starts and remove the forwarding rules when the VM stops.

To do so, we use this bash script to forward ports:

Guest_name=<VM name>
Guest_ipaddr=<VM IP address>
Host_ipaddr=<host IP address>
Host_port=(  '<host port 1>', '<host port 2>'  )
Guest_port=( '<guest port 1>', '<guest port 2>' )

length=$(( ${#Host_port[@]} - 1 ))
if [ "${1}" = "${Guest_name}" ]; then
   if [ "${2}" = "stopped" ] || [ "${2}" = "reconnect" ]; then
       for i in `seq 0 $length`; do
           iptables -t nat -D PREROUTING -d ${Host_ipaddr} -p tcp --dport ${Host_port[$i]} -j DNAT --to ${Guest_ipaddr}:${Guest_port[$i]}
           iptables -D FORWARD -d ${Guest_ipaddr}/32 -p tcp -m state --state NEW -m tcp --dport ${Guest_port[$i]} -j ACCEPT
       done
   fi
   if [ "${2}" = "start" ] || [ "${2}" = "reconnect" ]; then
       for i in `seq 0 $length`; do
           iptables -t nat -A PREROUTING -d ${Host_ipaddr} -p tcp --dport ${Host_port[$i]} -j DNAT --to ${Guest_ipaddr}:${Guest_port[$i]}
           iptables -I FORWARD -d ${Guest_ipaddr}/32 -p tcp -m state --state NEW -m tcp --dport ${Guest_port[$i]} -j ACCEPT
       done
   fi
fi