I can’t convert to whole

Asked

Viewed 161 times

-4

Perform a function that reads a text file containing a list of IP addresses and generates two other files, one containing valid IP addresses and the other containing invalid addresses. The format of an IP address is num1.num.num.num, where num1 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)
  • 6

    And what is the mistake? Which line?

  • File "C:/Users/Lucas/Pycharmprojects/Uff/file/5.py", line 21, in ips listaip.append(int(junta.strip()) Valueerror: invalid literal for int() with base 10: '0 n1'

  • The error message was very clear: there is a character \n in the middle of your string that cannot be converted to integer.

2 answers

2

I don’t know if I understand the question, but if your goal is only to validate ip, use the appropriate libraries for this, see the code below. Bonus: Information about the correctly typed ip.
(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 in repl.it.

0

To convert to integer just do a cast: int(variable).

You can also simplify the process by creating an IP Array using split(). See the code example (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!')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.