There is a long list of IP
10.2.186.8

10.2.186.64
10.2.186.65
172.7.143.6
172.7.143.33
172.7.143.34
172.7.143.35
etc.


I would like to receive the output:
10.2.186.8
10.2.186.64/31
172.7.143.6
172.7.143.33/30


How to implement it programmatically? To nearby standing IP turn on the network.
  • Specify, for example, you write that 10.2.186.64, 10.2.186.65 is 31 masks, but it can be any other mask, from where the program will take this data in the ip list there are no instructions on the mask? – Funny Frog Jun 19 '19 at 09:22
  • Chinese Paintball, in this online calculator you substitute a mask yourself, for example, it may be 10.0.1.0/8, or maybe 10.0.1.0/23, or maybe 10.0.1.0/17, the question is where the program will take the mask from. – Funny Frog Jun 19 '19 at 09:49
  • Chinese Paintball, and I'm talking about the same thing.Why 10.0.0.0, 10.0.0.1, 10.0.0.2, 10.0.0.3, is it 10.0.0.0/30, not 10.0.0.0/17? How the program guesses what kind of mask you have guessed.You will deal with this part, then it will be possible to answer your question, although it may not be necessary if the links above provide answers to all the questions. – Funny Frog Jun 19 '19 at 10:11
  • Funny Frog, I'm already tired of explaining the basics of networking to you :)
    Here is the solution

    >>>import ipaddress
    >>>list_of_ips=['10.0.0.0','10.0.0.1','10.0.0.2','10.0.0.3','10.0.0.5']
    >>>nets=[ipaddress.ip_network(_ip) for _ip in list_of_ips]
    >>>cidrs=ipaddress.collapse_addresses(nets)
    >>>print(list(cidrs))
    [IPv4Network('10 .0.0.0/30'), IPv4Network('10 .0.0.5/32')]
    >>>
    – Chinese Paintball Jun 19 '19 at 10:22
  • Chinese Paintball, and so it is impossible =):'10.0.0.0'/​​32,'10 .0.0.1/32','10.0.0.2/32','10.0.0.3/32','10.0.0.5/32' – Funny Frog Jun 19 '19 at 10:30
  • Funny Frog, have you read my question carefully?"How to shorten the list..."
    The goal was to get rid of a long list of ip addresses and, where possible, adjacent IPs could be turned into networks.
    – Chinese Paintball Jun 19 '19 at 10:32
  • Chinese Paintball, and what is the meaning of this action? Shorten to shorten or shorten according to the existing network topology? To simply shorten, they would write 0.0.0.0/0 right away and don’t waste their time)) – Funny Frog Jun 19 '19 at 10:35
  • Funny Frog, It is necessary to add a range of addresses to the whitelist not by one address. – Manic Office Jun 19 '19 at 11:58

1 Answers 1

>>>>import ipaddress
>>>list_of_ips=['10.0.0.0','10.0.0.1','10.0.0.2','10.0.0.3','10.0.0.5']
>>>nets=[ipaddress.ip_network(_ip) for _ip in list_of_ips]
>>>cidrs=ipaddress.collapse_addresses(nets)
>>>print(list(cidrs))
[IPv4Network('10 .0.0.0/30'), IPv4Network('10 .0.0.5/32')]