I can not convert to integer [closed]

-3

Make a function that reads a text file containing a list of IP addresses and generates two other files, one containing valid IP addresses and one containing the invalid addresses. The format of an IP address is num1.num.num.num , where num1 goes from 1 to 255 and num goes from 0 to 255.

def ips(arq1):
    ipsv=open('ipsv.txt','w')
    ipsi=open('ipsi.txt','w')
    c=0
    junta=""
    for ip in arq1:
        listaip = []
        for i in range(len(ip)):
            if ip[i]!=".":
               junta=junta+ip[i]
               junta=(junta)
               if len(junta)==3:
                   listaip.append(int(junta.strip()))
                   junta=""
            else:
                continue

        print(listaip)
        for x in listaip:
            if listaip[0]>=1 and listaip[0]<=255 and x>=0 and x<=255:
                ipsv.write(str(x))
            else:
                ipsi.write(str(x))
    ipsi.close()
    ipsv.close()

arq1=open('ips.txt','r')
ips(arq1)
    
asked by anonymous 20.06.2017 / 18:12

2 answers

2

I do not know if I understand the question, but if your goal is just to validate ip, use the appropriate libraries for this, see the code below. Bonus: Information about ip typed correctly

tl; dr )

from IPy import IP
import ipaddress

ip = input('Entre com o ip: ')
try: 
    ipaddress.ip_address(ip)
except ValueError:
    print ('Formato invalido do ip')
else:
    # Obter informações sobre o ip
    myip =  IP(ip)
    print ('Tipo de ip: ', myip.iptype(), '\nMáscara: ',
            myip.netmask(), '\nReverse name: ', myip.reverseName())

Entre com o ip:  192.168.5.3
Tipo de ip:  PRIVATE 
Máscara:  255.255.255.255 
Reverse name:  3.5.168.192.in-addr.arpa

# Entrando com o ip errado:
Entre com o ip:  192.299.5.3
Formato invalido do ip

Run this code on repl.it.

    
20.06.2017 / 19:18
0

To convert to integer, simply cast: int (variable).

In addition you can simplify the process by creating an IP Array using split (). See the code sample (Adapt to your code):

ip = '200.201.202.256'

nums = ip.split('.')

if len(nums) == 4:
    for n in nums:
        if 0 <= int(n) <= 255:
            print(n)
        else:
            print('IP Inválido!')
            break
else:
    print('IP Inválido!')
    
20.06.2017 / 18:32