iptables Commands

Topics · Published 2019-08-25 · Revised 2026-11-23
Reviewed corrections applied locally; pre-review version preserved separately · Joomla source

21,287 Total views across this article’s versions; includes the historical baseline where available.

The iptables command manages IPv4 packet-filtering and NAT rules in the Linux kernel. A rule can match addresses, protocols, interfaces, connection state, and other attributes before selecting a target.

This reference covers command structure, chain and rule operations, common match extensions, and targets. It uses the traditional iptables table and chain names. iptables -V identifies whether the installed command uses the legacy or nftables backend; kernel configuration and installed extensions determine which features are available.

The examples explain individual operations. They are not a complete firewall policy. Names, addresses, interfaces, rule order, and existing policies must fit the host where a rule will be used. Syntax fragments are labeled separately from complete commands.

For the complete option set, see iptables(8) and iptables-extensions(8). The companion command matrix summarizes valid combinations.

Command Line Syntax

A command that appends a rule has this general form:

iptables [-t TABLE] -A CHAIN [MATCHES] [-j TARGET [TARGET_OPTIONS]]

Other operations have different arguments: listing a chain does not require a match or a target. Long option names use two hyphens; option and chain names are case-sensitive.

This example appends an IPv4 input rule:

iptables -t filter -A INPUT -i eth1 -s 192.0.2.0/24 -j ACCEPT

filter is the table, INPUT is its chain for locally delivered packets, and -A tells the administration command to append a rule. The packet must arrive on eth1 with a source in 192.0.2.0/24. ACCEPT is the rule’s target. Earlier rules may already have decided the packet’s fate.

Use -s for a CIDR source prefix. An explicit address range instead requires a match such as -m iprange --src-range 192.0.2.10-192.0.2.20; a CIDR prefix is not an --src-range argument.

To remove this exact illustrative rule:

iptables -t filter -D INPUT -i eth1 -s 192.0.2.0/24 -j ACCEPT

iptables Commands and Chains

Select a table with -t or --table; omitting it selects filter. Chains belong to that table. INPUT is a chain name, not a table name.

OperationMeaning
-A / --appendAdd a rule to the end of a chain.
-I / --insertInsert before a rule number; the default position is 1. This is a list position, not a routing-rule priority.
-R / --replaceReplace the rule at a specified position.
-D / --deleteDelete a matching rule specification, or the rule at a specified position.
-C / --checkCheck whether a matching rule exists, without adding it.
-L / --listDisplay rules; combine with -n for numeric output and -v for detail.
-S / --list-rulesDisplay rules in command-style form.
-F / --flushRemove rules from a chain, or from all chains in the selected table when no chain is named. It does not reset built-in policies.
-Z / --zeroReset packet and byte counters.
-N / --new-chainCreate a user-defined chain in the selected table.
-X / --delete-chainDelete an empty, unreferenced user-defined chain.
-P / --policySet a built-in chain policy to ACCEPT or DROP.
-E / --rename-chainRename a user-defined chain.

Actions upon Chains

Chain-management syntax uses the chain name directly:

iptables -t TABLE -N NEW_CHAIN
iptables -t TABLE -E OLD_CHAIN NEW_CHAIN
iptables -t TABLE -F CHAIN
iptables -t TABLE -X CHAIN
iptables -t TABLE -P BUILTIN_CHAIN ACCEPT

A new user-defined chain is not automatically reached by packets: another rule in the same table must jump or go to it. Before deleting it, remove rules that reference it and remove its contents. Flushing a built-in chain with a DROP policy leaves that policy in effect.

Actions upon Rules

Rule-management forms include:

iptables -t TABLE -A CHAIN MATCHES -j TARGET
iptables -t TABLE -I CHAIN POSITION MATCHES -j TARGET
iptables -t TABLE -R CHAIN POSITION MATCHES -j TARGET
iptables -t TABLE -D CHAIN POSITION
iptables -t TABLE -C CHAIN MATCHES -j TARGET

Rule numbers start at 1 and can change after insertions or deletions. Inspect the selected table and chain before relying on a number. For example, these commands only display the current filter rules:

iptables -t filter -L INPUT -n -v --line-numbers
iptables -t filter -S INPUT

Parameters

The common rule parameters are:

ParameterMeaning
-s / --source ADDRESS[/PREFIX]Match the source address or network.
-d / --destination ADDRESS[/PREFIX]Match the destination address or network.
-p / --protocol PROTOCOLMatch an IP protocol such as tcp, udp, or icmp. TCP/UDP port options do not apply to ICMP.
-i / --in-interface NAMEMatch the incoming interface in PREROUTING, INPUT, or FORWARD.
-o / --out-interface NAMEMatch the outgoing interface in FORWARD, OUTPUT, or POSTROUTING.
-m / --match NAMELoad a match extension and use its options.
-j / --jump TARGETSelect a verdict, target extension, or user-defined chain.
-g / --goto CHAINTransfer to a user-defined chain without returning to the next rule in this chain.

Not every listed chain exists in every table. Multiple match conditions in one rule must all succeed. Where an option supports inversion, ! negates that particular condition.

iptables Extensions

Extensions provide additional matches and targets. The userspace iptables program parses the command and installs the rule. The kernel processes packets against the installed rules; it does not launch an external filter program for each packet.

Match extensions answer whether a rule applies. Target extensions perform an operation after its matches succeed. A target may continue rule traversal or terminate it, depending on the target.

Extension Syntax

Match and target fragments have different forms:

-m MATCH_NAME MATCH_OPTIONS
-j TARGET_NAME TARGET_OPTIONS

For example, -m conntrack --ctstate ESTABLISHED,RELATED tests connection-tracking state, whereas -j CONNMARK --set-mark 32 modifies a connection mark. Names and case matter.

Protocol-specific matching can be loaded implicitly: -p tcp --dport 443 makes the TCP destination-port option available. iptables -m MATCH_NAME -h displays help for an installed match.

Match Extensions

These common matches select packets without themselves accepting, dropping, or marking them:

MatchWhat it examines
connmarkThe mark stored on a tracked connection.
conntrackConnection-tracking state, tuples, status, and related metadata.
iprangeAn explicit source or destination address interval.
macThe source Ethernet address on suitable received packets.
markThe current packet mark.
multiportA list of transport-layer ports or port ranges.
ownerThe owner of a socket associated with locally generated traffic.
stateA smaller set of conntrack state tests.

connmark

The connmark match reads the mark on the tracked connection:

-m connmark --mark 32

Use CONNMARK to set or copy connection marks. The mark match reads a packet mark instead. A connection mark is not automatically copied to every packet; use an explicit restore operation when packet-based routing or another consumer needs it.

conntrack

The conntrack match inspects the kernel’s tracking information. A typical fragment is:

-m conntrack --ctstate ESTABLISHED,RELATED
StateMeaning
NEWTracking has not yet observed traffic in both directions for this flow. This can include retransmissions, not just the first packet.
ESTABLISHEDTracking has observed both directions. This is not a promise that an application transaction or TCP handshake has completed.
RELATEDThe packet is associated with an existing tracked connection, such as a related ICMP error or an expected auxiliary flow.
INVALIDThe packet cannot be assigned to a valid tracked connection.
UNTRACKEDTracking has been explicitly bypassed, for example with CT --notrack.
SNAT / DNATVirtual states that identify source or destination translation by comparing the original and reply tuples.

Other options inspect addresses and ports in the original/reply tuples or tracking status. --ctexpire tests the remaining connection-tracking lifetime in seconds; it is unrelated to the IPv4 TTL field.

Connection tracking is a kernel facility used by stateful filtering and NAT. A rule does not have to contain -m conntrack for the kernel to track its packets, but tracking support must be enabled and the traffic must not have been exempted.

iprange

Use iprange for an inclusive address interval. These are match fragments:

-m iprange --src-range 192.0.2.10-192.0.2.20
-m iprange --dst-range 198.51.100.10-198.51.100.20

Use -s 192.0.2.0/24 or -d 198.51.100.0/24 when a CIDR prefix describes the desired network.

mac

The mac match tests an Ethernet source address, for example:

-m mac --mac-source 02:00:00:00:00:01

It is useful for suitable Ethernet packets received through PREROUTING, INPUT, or FORWARD. The observed address belongs to the sender on that link; after a routed hop it is normally the next-hop router’s address, not the original Internet host’s address. MAC addresses can be changed or spoofed, so this is not proof of a device’s identity.

mark

Matches packets with a previously associated mark value. For the methods discussed here, a packet mark may be assigned in either of two ways:

  1. The current connection was previously marked with the CONNMARK target extension, and its mark was copied to the current packet with CONNMARK --restore-mark
  2. The current packet was previously marked via the MARK target extension

An ip rule fwmark selector matches an existing packet mark; it does not set one.

The syntax of the mark match extension is: -m mark –mark {value}

multiport

Use multiport for comma-separated ports and ranges:

-p tcp -m multiport --dports 22,80,443,8000:8005
-p udp -m multiport --sports 53,123

--sports tests source ports, --dports tests destination ports, and --ports tests either. A list has at most 15 slots, with a range consuming two slots. Ranges use a colon, not a hyphen. This match supports TCP, UDP, UDP-Lite, DCCP, and SCTP; it does not give ICMP port numbers.

owner

The owner match inspects ownership of the socket associated with locally generated packets. It is available in OUTPUT and POSTROUTING, where those chains exist in the selected table. Examples are filter/OUTPUT and mangle/POSTROUTING; there is no filter/POSTROUTING chain.

-m owner --uid-owner 1000
-m owner --gid-owner 1000-1005

Numeric UID/GID ranges use a hyphen. Forwarded traffic has no local originating socket, and some locally generated kernel traffic has no matching user-owned socket. This match does not identify the user on a remote machine.

state

The state match is a subset of conntrack. It supports INVALID, ESTABLISHED, NEW, RELATED, and UNTRACKED through --state:

-m state --state ESTABLISHED,RELATED

The equivalent state test with the broader interface is -m conntrack --ctstate ESTABLISHED,RELATED. Use conntrack when you also need its tuple, status, or other metadata tests. The current manual still documents state; no blanket removal date is assumed here. See endnote 1.

–source-port

TCP and UDP provide --source-port (--sport) and --destination-port (--dport). Each ordinary option accepts one port or one colon-separated range:

-p tcp --sport 1024:65535
-p udp --dport 53

For a list, use multiport, for example -p udp -m multiport --sports 53,123. A comma-separated list is not an ordinary --sport argument. See iptables Protocols for additional examples.

Target Extensions

A target is selected with -j. ACCEPT, DROP, and RETURN are core verdicts; REJECT is an extension. Target extensions include mark operations, tracking configuration, and NAT. A user-defined chain can also be the destination of a jump.

Port selectors such as --sport are match options, not targets. CONNMARK changes or copies a connection mark; the lowercase connmark match only tests it.

CONNMARK

CONNMARK operates on the connection mark associated with tracked traffic. With the default full-width masks, these fragments have the following effects:

Target fragmentEffect
-j CONNMARK --set-mark 32Set the connection mark to 32.
-j CONNMARK --save-markCopy the packet mark into the connection mark.
-j CONNMARK --restore-markCopy the connection mark into the packet mark.

Use the mangle table for these copying examples; the manual documents --restore-mark there. Masks can restrict which bits are affected. Packet marks and connection marks are separate local kernel metadata, not fields transmitted in an IP header. Setting one does not implicitly update the other.

Choose the restore hook to suit the consumer: incoming policy routing needs the packet mark before route selection, while locally generated traffic can use mangle/OUTPUT. A connection mark requires a tracked connection; bypassing tracking removes that basis.

CONNSECMARK

CONNSECMARK copies security labels between a packet and its tracked connection. These labels are separate from numeric packet/connection marks used for policy routing.

--save copies a packet security label to a connection that is not already labeled. --restore copies a connection security label to a packet that is not already labeled. It does not unconditionally replace an existing label.

Use the security table, or mangle where supported for compatibility. These operations work with the system’s security labeling policy; they do not provide a way to bypass or emulate SELinux.

CT

The CT target configures how connection tracking handles a packet and, when applicable, the template used to create a tracking entry. It belongs in the raw table, before normal tracking, using PREROUTING for received traffic or OUTPUT for locally generated traffic.

The fragment -j CT --notrack bypasses tracking for matching packets. Other options select helpers, zones, or timeout policies. Skipping tracking does not skip later firewall rules, and it affects features that need tracking, including stateful NAT. Any deliberate untracked flow must be considered in both directions.

DNAT (Destination Network Address Translation)

DNAT changes a connection’s destination address, destination port, or both. Use it in nat/PREROUTING, nat/OUTPUT, or a user-defined chain reached only from those hooks. It is not limited to public-to-private address translation.

This illustrative rule changes only the destination port from 8080 to 80 for TCP traffic arriving on eth0 for 198.51.100.10:

iptables -t nat -A PREROUTING -i eth0 -d 198.51.100.10 -p tcp --dport 8080 -j DNAT --to-destination :80

The destination address remains 198.51.100.10. An outgoing-interface match (-o) is not available in PREROUTING, before the route is selected. This rule does not itself permit delivery or forwarding. The address, service, routing, and filtering must already be configured for the intended use.

Remove the example rule with:

iptables -t nat -D PREROUTING -i eth0 -d 198.51.100.10 -p tcp --dport 8080 -j DNAT --to-destination :80

Removing a NAT rule does not erase translations already recorded for existing connections.

DNAT Address Pools

A DNAT target can specify an address pool, such as the fragment:

-j DNAT --to-destination 192.0.2.10-192.0.2.20

The initial NAT decision establishes a connection binding; later packets follow that binding. An address range is not a health-checked load balancer and does not promise selection of the least-used server. A rule still needs appropriate protocol/address/port matches, routing, and filtering. Use a load-balancing design with explicit health checks when server availability must guide selection.

MARK

A numeric field (32-bit integer) used to mark (flag) a packet by associating a value with it. The MARK command is used by iptables to set a packet mark. It is the same thing as fwmark (FireWall Mark) in ip rules.

The MARK target sets a packet mark; ip rule fwmark matches it when selecting a routing policy. Packet marks may also be read by iptables.

For the policy-routing examples here, use the MARK target in the mangle table. Where you place the rule depends on where the packet originates.

The syntax is: –set-mark

Example:

… -j MARK –set-mark 32

MASQUERADE

MASQUERADE performs source NAT using an address of the outgoing interface. Use it in nat/POSTROUTING, including user-defined chains reached only from there. It is useful when the interface address changes; a fixed source address is usually expressed with SNAT.

The chosen address need not be public, and it is not the upstream router’s address. A target fragment is -j MASQUERADE. To request a translated port interval, use an option such as --to-ports 40000-41000 with an appropriate TCP, UDP, DCCP, or SCTP protocol match. The protocol requirement applies to the port option, not to every MASQUERADE rule.

NOTRACK

NOTRACK is equivalent to CT --notrack. It belongs in the raw table’s PREROUTING or OUTPUT path, before normal tracking:

-j NOTRACK

It exempts matching packets from connection tracking, not from subsequent filtering. See CT for the consequences for state and NAT.

REJECT

REJECT drops the matching packet and requests an error response, subject to the protocol’s response rules. In the traditional IPv4 iptables implementation it is a filter target for INPUT, FORWARD, and OUTPUT, including appropriately reached user-defined chains.

The default IPv4 response is ICMP port unreachable. The fragment -p tcp -j REJECT --reject-with tcp-reset requests a TCP reset and therefore requires a TCP match. A rejected packet is not the same operation as deleting a conntrack entry or issuing a command to close every packet in a connection.

The extension manual advises dropping INVALID packets rather than indiscriminately rejecting them, because a late invalid packet may otherwise provoke a response that disrupts a healthy connection.

SECMARK

SECMARK sets a packet security label for a security subsystem such as SELinux. Its syntax is:

-j SECMARK --selctx SECURITY_CONTEXT

SECURITY_CONTEXT must be a valid context authorized by the installed security policy. A context copied from another host is not necessarily valid. Use the security table, or mangle for supported compatibility cases. This target does not enable SELinux on a host without the required subsystem and policy, and it is not a policy bypass.

The Linux SECMARK implementation validates the context and relabel permission before accepting the rule.

SNAT (Source Network Address Translation)

SNAT changes the source address, source port, or both for a tracked connection. It is valid in nat/POSTROUTING and, on Linux 2.6.36 and later, nat/INPUT, including user-defined chains reached only from those hooks.

A source-address target fragment is:

-j SNAT --to-source 198.51.100.10

The fragment -p udp -j SNAT --to-source :40000 changes the source port only; it does not redirect the packet to destination port 40000. Port translation requires a compatible TCP, UDP, DCCP, or SCTP match. Source-address ownership/routing and the return path still need to fit the topology.

As with DNAT, a connection’s established binding handles later packets and reverse translation. Changing a rule does not rewrite an existing connection’s binding.

SNAT Address Pools

An SNAT address pool can be expressed as:

-j SNAT --to-source 198.51.100.10-198.51.100.20

The kernel chooses a translation when establishing the NAT binding. The pool does not promise round-robin or least-used-address scheduling, nor does it monitor upstream availability. It supplies possible translated addresses; it is not a failover configuration. All selected addresses must have a valid return path.

Actions and Targets

Matches determine whether a rule applies; the target determines what follows. A target can have its own options after its name, such as -j MARK --set-mark 32, so a rule does not necessarily end with the target name.

Both -j/--jump and -g/--goto can transfer processing to a user-defined chain in the same table. Their return behavior differs.

Goto

-g CHAIN or --goto CHAIN transfers processing to a user-defined chain. When that chain returns, traversal does not resume at the rule after the goto in the current chain. It returns to the caller that entered the current chain with a jump, if one exists. If no such caller remains, the built-in chain’s policy applies.

The syntax fragment is -g CUSTOM_CHAIN. The chain must already exist in the selected table.

Jump

-j CHAIN or --jump CHAIN enters a user-defined chain and keeps a return point. RETURN, or reaching the end of that user-defined chain, resumes at the rule after the jump.

For targets rather than chain names, behavior depends on the target. MARK changes metadata and continues. DROP discards the current packet. ACCEPT ends this table traversal with acceptance, but does not guarantee that a later table or hook cannot drop the packet. Reaching the end of a built-in chain applies that chain’s policy.

Endnotes

  1. The current extension manual documents both state and conntrack; this reference uses conntrack for its broader interface. Historical discussions of deprecation do not establish that state has been removed from the reader’s system.

The main manual specifies command forms, table membership, and jump/goto behavior. The Linux IPv4 REJECT implementation supplies the traditional filter-table restriction. Backend and kernel support should be checked with the installed command’s help before applying a rule.