Created
January 24, 2017 00:27
-
-
Save berenoguz/78f2742d64e6c01e3b43d4be928c3d65 to your computer and use it in GitHub Desktop.
A simple python function to return `iptables -m multiport` compatible shortest representation of a given list on integers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Author: Beren Oguz <beren@berkeley.edu> | |
# function: multiport_represent_ports | |
# input: arr, a list of port numbers, their type must be int | |
# output: shortest representation that can be passed to `iptables -m multiport` | |
def multiport_represent_ports(arr): | |
min_max = [[i, i] for i in range(len(arr))] # we keep track of min and max of ranges | |
port2id = dict() # port number -> array index | |
id2port = dict() # array index -> port number | |
arr = sorted(arr) | |
i = 0 | |
for port in arr: | |
if port - 1 in port2id: | |
min = min_max[port2id[port - 1]][0] # min of range | |
min_max[min][1] = i # make min's max this port | |
min_max[i][0] = min # make my min this min | |
port2id[port] = i | |
id2port[i] = port | |
i += 1 | |
output = [] | |
total_ports = 15 # we start from 15 so that if len(arr) == 0, output is [] | |
i = 0 | |
while True: | |
if i >= len(arr): # we're done | |
return output | |
current = min_max[i] # current port | |
if total_ports % 15 == 0: # maximum amount of ports reached | |
output.append('') | |
if current[0] == current[1]: # not a range | |
current_str = str(id2port[current[0]]) | |
if total_ports % 15 == 0: | |
output[-1] = output[-1] + current_str | |
else: | |
output[-1] = output[-1] + "," + current_str | |
else: # range | |
current_str = str(id2port[current[0]]) + ":" + str(id2port[current[1]]) | |
if total_ports % 15 == 0: | |
output[-1] = output[-1] + current_str | |
else: | |
output[-1] = output[-1] + "," + current_str | |
i = current[1] | |
total_ports += 1 | |
total_ports += 1 | |
i += 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment