iptables multiple source IPs in single rule

Solution 1:

This is only possible if you can aggregate the source IP's you want into a contiguous range. eg

iptables -A INPUT -s 192.168.0.0/24 -d 192.168.0.5 -p tcp -j ACCEPT

If you cannot find a common netmask that covers the IP's you want, you'll have to write several identical rules to do what you want.

There are several iptables frameworks around which can deal with the low level of writing the iptables rules, allowing you to define your rules at a more symolic level. Shorewall is a common one that ships with most current linux distributions.

Solution 2:

To add multiple sources in a single command I would do this:

iptables -t filter -A INPUT -s 192.168.1.1,2.2.2.2,10.10.10.10 -j ACCEPT

iptables will automatically translate it into multiple rules.

Solution 3:

The original question is from May 2009, but since May 2011 the Linux kernel has had a feature to address this need called ipset.

Here is an example creating an ipset, adding addresses to it, and then using it in a firewall rule:

ipset -N office365 iphash

ipset -A office365 132.245.228.194
ipset -A office365 132.245.77.34
ipset -A office365 132.245.48.34
ipset -A office365 132.245.68.242
ipset -A office365 132.245.55.2
ipset -A office365 40.101.17.98
ipset -A office365 132.245.48.18
ipset -A office365 132.245.229.114
ipset -A office365 132.245.196.34
ipset -A office365 132.245.56.114

iptables -A OUTPUT -m set --match-set office365 dst -j ACCEPT

See man iptables and man ipset for more info.

Solution 4:

you can use the iprange module in combination with '--src-range' like for e.x.:

-A INPUT -i eth0 -m iprange --src-range 192.168.1.90-192.168.1.101 -j ACCEPT

Source: iptables 1.4.7 man page

   iprange
   This matches on a given arbitrary range of IP addresses.

   [!] --src-range from[-to]
          Match source IP in the specified range.

   [!] --dst-range from[-to]
          Match destination IP in the specified range.

(i know this is like a 4 year old question, but just to answer for anyone who seeks this on the net)