Python script to convert network number/subnet mask into available IP network segment

1. Use the ipaddress library to convert IP network segments

import ipaddress
import threading
import re
#Introduce regular expression module
import os
importsys
#Performance card explosion version

def cal_ip(ip_net):
    try:
        print(ip_net)
        net = ipaddress.ip_network(ip_net, strict=False)
        print('IP version number: ' + str(net.version))
        print('Is it a private address: ' + str(net.is_private))
        print('Total number of IP addresses: ' + str(net.num_addresses))
        print('Total number of available IP addresses: ' + str(len([x for x in net.hosts()])))
        print('Network number: ' + str(net.network_address))
        print('Starting available IP address: ' + str([x for x in net.hosts()][0]))
        print('Last available IP address: ' + str([x for x in net.hosts()][-1]))
        print('Available IP address range: ' + str([x for x in net.hosts()][0]) + '-' + str([x for x in net.hosts()][ -1]))
        print('Mask address: ' + str(net.netmask))
        print('Anti-mask address: ' + str(net.hostmask))
        print('Broadcast address: ' + str(net.broadcast_address))
        LineIP = str([x for x in net.hosts()][0]) + '-' + str([x for x in net.hosts()][-1])
        line_IP.append(str([x for x in net.hosts()][0]) + '-' + str([x for x in net.hosts()][-1]) + '\ \
')
        #ip_net = ""
        #returnip_net
    except ValueError:
        print('Your input format is wrong, please check!')

if __name__ == '__main__':
    line_IP = []
    #Read the file to get the IP and mask
    lines = open('ip_mask.txt','r').readlines() #Open the file and read each line
    #print(lines)
    
    #ip_net = '192.168.1.1/24'
    #thread = threading.Thread(target=cal_ip)
    #thread.start()
    #thread.join()
    for s in lines:
        s = s.strip()
        cal_ip(s)
    with open("ip_mask_2.txt", mode='w', encoding='utf-8') as fp:
        for f in line_IP:
            fp.write(f) # write is to write
        #fp.close() # Close the file
    print("Writing completed")

        
            
        

The above is to use python’s original ipaddress library file to process the obtained network address/mask and obtain the IP range segment, which can simplify the need to write the network segment provided by the customer into a network segment form.

2. Use algorithms to process network segment conversion into P network segments

@Author [email protected]
import re
#Introduce regular expression module
import os
importsys

#Performance optimization

line_IP_cache = []
line_IP = []
def Masker(mask,NetorHost):
    global LastIP,FirstIP,line_IP
    if NetorHost==0: #Calculate network part series
        MyNetworkt1=str(IP2[0:mask]) + str(str(NetorHost)*(32-int(IPMask)))
        print('Step 4:' + str(MyNetworkt1))
        # Set all the host parts of the binary IP to 0 based on the number of mask bits to calculate the first host
        FirstIPt1=str(IP2[0:mask]) + str(str(NetorHost)*(32-int(IPMask)-1)) + str(1)
        #Binary first host IP
        print('Step 5:' + str(FirstIPt1))
        MyNetwork2=[]
        FirstIPt2=[]
        i=0
        while i<=3:
            MyNetwork2.append(int(MyNetworkt1[i*8:(i + 1)*8],2))
            #Divide the binary form network segment MyNetwork1 into four segments and convert it to decimal form.
            FirstIPt2.append(int(FirstIPt1[i*8:(i + 1)*8],2))
            #Divide the first host in binary form into four segments and convert it to decimal form.
            i + =1
        MyNetworkt3=str(MyNetwork2)[1:-1].replace(',','.')
        #The network segment is rewritten as a dot fraction, not a comma fraction.
        MyNetwork=MyNetworkt3.replace(' ','')
        #Network segments further remove spaces
        FirstIPt3=str(FirstIPt2)[1:-1].replace(',','.')
        #The first host is rewritten as a dot fraction, not a comma fraction.
        FirstIP=FirstIPt3.replace(' ','')
        #The first host further removes spaces
        print('Step 6: Network address ' + str(MyNetwork))
        print('Step 7: First host ' + str(FirstIP))
        
    else: #Computing host part series
        MyNetworkt1=str(IP2[0:mask]) + str(str(NetorHost)*(32-int(IPMask)))
        print('Step 8:' + str(MyNetworkt1))
        #Binary form of broadcast address
        LastIPt1=str(IP2[0:mask]) + str(str(NetorHost)*(32-int(IPMask)-1)) + str(0)
        #Binary form of the last host address
        print('Step 9:' + str(LastIPt1))
        MyNetwork2=[]
        LastIPt2=[]
        i=0
        while i<=3:
            MyNetwork2.append(int(MyNetworkt1[i*8:(i + 1)*8],2))
            #Broadcast address conversion decimal
            LastIPt2.append(int(LastIPt1[i*8:(i + 1)*8],2))
            #Convert the last host address to decimal
            i + =1
        MyNetworkt3=str(MyNetwork2)[1:-1].replace(',','.')
        #point fraction
        MyNetwork=MyNetworkt3.replace(' ','')
        #Remove spaces
        LastIPt3=str(LastIPt2)[1:-1].replace(',','.')
        LastIP=LastIPt3.replace(' ','')
        print('Step 10: Last host ' + str(LastIP))
        print('Step 11: Broadcast address ' + str(MyNetwork))
        lineIP = str(FirstIP + "-" + LastIP + "\\
")
        line_IP_cache.append(lineIP)
        print("Available address range:",lineIP)
        print("")
        line_IP = line_IP_cache
        

#Read each line of data in txt, such as 192.168.1.0/24
lines = open('ip_mask.txt','r').readlines() #Open the file and read each line
print(lines)
j=1
for s in lines :
    print("Processing",j,"th")
    s = s.strip()
    if "/" in s[-2:]:
        #print(s[-1:])
        IPAddr=s[:-2]
        IPMask=s[-1:]
        print("IP:",s[:-2])# Output the processed row data and obtain the IP network number address
        print("MASK:",s[-1:])# Output the processed row data and obtain the subnet mask
    else:
        IPAddr=s[:-3]
        IPMask=s[-2:]
        print("IP:",s[:-3])# Output the processed row data and obtain the IP network number address
        print("MASK:",s[-2:])# Output the processed row data and obtain the subnet mask
    
    
    #Here is the assignment to the IP variable
    #Data processing
    IP10L = re.findall(r'\d*', IPAddr) #Use regular expressions to pick out the four decimal numbers of the IP address
    for x in IP10L:
        IP10L.remove('')
    print('First step:' + str(IP10L))
    #Convert the IP address into a four-digit decimal number sequence

    IP2L=[]
    IP2=''
    for x in IP10L:
        #MyBin=str(bin(int(x))).strip('0b') #This method is easy to accidentally kill the following 0
        MyBin = str(bin(int(x)))[2:]
        MyZero='0'*(8-len(MyBin)) #The number of digits of 0 needs to be added in front
        IP2L.append(str(MyZero) + (bin(int(x)))[2:])
    for x in IP2L:
        IP2=IP2 + str(x)
    print('Step 2:' + str(IP2L))
    print('Step 3:' + str(IP2))
    #Convert the IP address into a four-digit binary sequence, and finally use an empty string to splice it into a whole

    Masker(int(IPMask),0) #Network address, that is, the host part is equal to 0
    Masker(int(IPMask),1) #Host address, that is, the host part is not 0
    j=j+1
with open("ip_mask_2.txt", mode='w', encoding='utf-8') as fp:
    for f in line_IP:
        fp.write(f) # write is to write
    #fp.close() # Close the file
    print("Writing completed")
        

This second method calls the method and stores the returned data in the ip_mask_2.txt file after execution. It does not involve threads and can be added according to your own ideas.

Before standardization

After standardization

python returns