Linux: Iptables Forward Multiple Ports

How do I forward multiple ports using Linux iptables based firewall?

The Linux iptables comes with MATCH EXTENSIONS which can use extended packet matching modules. The multiport match module matches a set of source or destination ports. Up to 15 ports can be specified. A port range (port:port) counts as two ports. It can only be used in conjunction with -p tcp or -p udp options.

ADVERTISEMENTS

Syntax

The syntax is as follows for the destination port:

iptables -A tableName -p tcp  --match multiport --dports port1,port2 -j ACCEPT
iptables -A tableName -p udp  --match multiport --dports port1,port2 -j DROP
iptables -A tableName -p protocol  --match multiport --dports portRange1:PortRange2 -j ACCEPT

The syntax is as follows for the source port:

iptables -A tableName -p tcp  --match multiport --sports port1,port2 -j ACCEPT
iptables -A tableName -p udp  --match multiport --sports port1,port2 -j DROP
iptables -A tableName -p protocol  --match multiport --sports portRange1:PortRange2 -j ACCEPT

Examples

The following will accept all traffic from TCP port 80,22,53:
/sbin/iptables -A INPUT -p tcp --match multiport --dports 80,22,53 -j ACCEPT
The following will accept 1024 to 3000 port range:
/sbin/iptables -A INPUT -p tcp --match multiport --dports 1024:3000 -j ACCEPT
Finally, save the changes:
# service iptables save
OR
# iptables-save > /path/to/your/iptables/settings/file

🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNCentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
3 comments… add one
  • libin Jan 15, 2015 @ 1:57

    Multiports is useful in iptables saving statements.

  • E Nov 18, 2015 @ 11:20

    Examples shows only ACCEPT and REJECT despite the title with FORWARD :(

  • Phoenix May 10, 2016 @ 21:10

    Like E, I came here looking for forwarding rules, not ACCEPT and DROP. Change the article title.

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.