How can I block access on all port except one eg 9999 to a server from specific IP eg ?

iptables -A INPUT -s -j DROP will block all of ports.

Is there a possibility to block port range for specific IP?

migrated from stackoverflow.com Feb 10 '17 at 11:34

This question came from our site for professional and enthusiast programmers.


Yes of course there is!

iptables rules apply in order. So you may start by a very restrictive policy for your chain, and then allow traffic on specific ports.

You may first set default CHAIN policies like : (by default they are set as ACCEPT)

iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP

This way you're configuring every CHAIN to reject anything. Then you can allow traffic by just one port, or just some network segment, as you like:

iptables -A INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT

INPUT is the name of the CHAIN you're adding the rule, -i is for specifying which interface the rule applies to (eth0 in the example) -p is used to specify the protocol (tcp) in this case, with --dport you specify on which port you are allowing traffic, -m state instructs the firewall to look at the connection state, this is for you to be able to use --state NEW,ESTABLISHED which are the two states on which the connection is permitted, finally -j ACCEPT tells the firewall that connections made that match the previously described rule will be accepted.

As your final question asks for ranges of IP and/or Ports the way to acomplish this is by using --dport 80:10010 (rule applies to ports from 80 to 10010) and for the IP range you can use -m iprange --src-range so the rule will apply to any traffic comming from any ip in the range -

Full working example:

iptables -A INPUT -i eth0 -p tcp --dport 80:10010 -m iprange --src-range -m state --state NEW,ESTABLISHED -j ACCEPT

Your Answer

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