Allow iptables to allow ip range only on specifc port

The last line you have in there should work, you just need to make sure you have a -p protocol in there, as --dport doesn't work as a option on its own.

iptables -A INPUT -m iprange --src-range 10.50.10.20-80 -p tcp --dport 12345 -j ACCEPT

Alternatively, install ipset and you will be able to change the list of IP addresses without messing your iptables rules:

ipset -N AllowedSources ipmap --network 10.50.10.0/24
for i in $LIST_OF_ALLOWED_SOURCES; do ipset -A AllowedSources $i; done
iptables -A INPUT -m set --match-set AllowedSources src -p tcp --dport 12345 -j ACCEPT

Now, if you need to add another allowed source:

ipset -A AllowedSources a.b.c.d

Or, you need to 'drop' a host from the allowed sources:

ipset -D AllowedSources e.f.g.h

You can save your sets:

ipset --save > /etc/ipset.conf

Which you can restore during boot, before you implement your iptables (or else, iptables will complain!):

ipset --restore < /etc/ipset.conf

You can even create an IP set that will match against source IP and destination port, e.g.:

ipset -N AllowedAccess ipporthash --network 10.50.0.0/16
# These hosts may access port 12345
for i in $LIST_OF_ALLOWED_TO_12345; do ipset -A AllowedAccess $i,12345; done
# These hosts may access port 23456
for i in $LIST_OF_ALLOWED_TO_23456; do ipset -A AllowedAccess $i,23456; done
# These hosts may access port 34567
for i in $LIST_OF_ALLOWED_TO_34567; do ipset -A AllowedAccess $i,34567; done
# Now that the IP set has been created, we can use it in iptables
iptables -A INPUT -m set --match-set AllowedAccess src,dst -j ACCEPT
# Note that we use "src,dst", meaning that we want to match source IP, but
# destination port
# Also note, if you need to match against a single port, the ipmap method
# will be slightly faster.

More on ipset: http://ipset.netfilter.org/

If you are using Ubuntu, you can't install the ipset package from its repo. Use my tip: http://pepoluan.posterous.com/powertip-howto-install-ipset-on-ubuntu


You've got the basic idea right, you can combine them into one rule like that.

However, despite what some answers say, you shouldn't use a range like 10.50.10.20-80 (it will expand to 10.50.10.20-80.0.0.0 - use the iptables command to check). You need to use the full IP address in the range e.g. 10.50.10.20-10.50.10.80.

Also, if you specify a port number, you need to state a protocol that supports ports, so the revised rule would be:

iptables -A INPUT -p tcp -m iprange --src-range 10.50.10.20-10.50.10.80 --dport 12345 -j ACCEPT

Documentaion on iprange: https://www.frozentux.net/iptables-tutorial/chunkyhtml/x2702.html#TABLE.IPRANGEMATCH