How to block outgoing packets to IP range with iptables?

I want to block outgoing packets to an IP range but the iptables command I'm using does not seem to work.

 sudo iptables -P OUTPUT ACCEPT sudo iptables -A OUTPUT -s 157.240.0.0/16 -j REJECT sudo iptables -A OUTPUT -s 31.13.0.0/16 -j REJECT sudo iptables -A OUTPUT -s 192.229.0.0/16 -j REJECT sudo iptables -A OUTPUT -s 104.244.0.0/16 -j REJECT

Isn't what I need to do to

  1. allow all packets for the entire range
  2. then block specific subsets of the entire range?

1 Answer

-s means "source". By "outgoing packets to IP range" you most likely mean "destination". Change each -s to -d.

Also keep in mind -A appends a rule to the end of the chain. Rules are processed starting from the head. The rule you append to the end will be processed last (if the flow ever gets to it). Rules previously (and still) existing in the chain may apply and handle the packets you want to block. Use -I instead of -A to add a rule at the head of the chain.

If you suspect you may have added some unwanted rules then investigate with iptables -S OUTPUT and delete them with -D. There is also -F to flush and start anew.

See man 8 iptables for details.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like