How to route all IPv4s for a given hostname via a specific gateway

This is useful for example for circumventing VPN for specific hosts.

See Linux: How to route specific hosts around VPN for a simplified approach for hosts with a single IP address.


add_routes_for_host() {
    local hostname="$1"
    local gateway="$2"
    local metric="$3"

    # Get all IPv4 addresses for the hostname
    local ips=$(dig +short "$hostname" A | grep -E '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$')
    
    if [ -z "$ips" ]; then
        echo "No IPv4 addresses found for $hostname"
        return 1
    fi

    # Add route for each IP
    for ip in $ips; do
        if [ -z "$ip" ]; then
            continue
        fi

        if sudo ip route add "$ip/32" via "$gateway" metric "$metric"; then
            echo "Added route for $ip via $gateway"
        else
            echo "Failed to add route for $ip"
        fi
    done
}

Example usage

add_routes_for_host "security.ubuntu.com" "192.168.1.1" "10"