Python and the ipaddress module

Asked

Viewed 128 times

0

Hello,

I have a TXT file containing 340,000 lines of decimal IP addresses, for example: 16777262. Using the ipaddress module I can convert the decimal to the punctuated format '1.0.0.46'. As evidence below:

>>> ipaddress.ip_address(16777262).__str__()
'1.0.0.46'

When I create the code for Python to read each line and convert the decimal to IP, I’m getting the following error:

Code:

import ipaddress

source_file = open('dcim_to_ip.txt')

for decimal_line in source_file:
    decimal = decimal_line.rstrip('\n')
    ipaddress.ip_address(decimal).__str__()

Error:

ValueError: '16777262' does not appear to be an IPv4 or IPv6 address

I feel like I’m doing something wrong in the way the information is read from the TXT file and passed to the ipaddress module. How can I advance here?

1 answer

0

Good morning, Renan!

I have no experience with this package, but the document "An Introduction to the ipaddress module" indicates that the function ip_address creates an instance of IPv4Address or of IPv6Address, from an integer or string formatted as a valid ip.

It means that:

The code below works because the parameter is an integer value (as in your first example)

>>> ipaddress.ip_address(19216801)
IPv4Address('1.37.57.161')

This code also works because although the parameter is a string, it is formatted as an ip address

>>> ipaddress.ip_address('192.168.0.1')
IPv4Address('192.168.0.1')

This example is equivalent to what you are trying to do, which is to pass a string not formatted as ip

>>> ipaddress.ip_address('19216801')
ValueError: '19216801' does not appear to be an IPv4 or IPv6 address

When you are iterating the lines of your file, each value is a string. Just convert to an integer first. You do not even need to explicitly remove \n if you want.


Solution

for decimal_line in source_file:
    ipaddress.ip_address(int(decimal_line)).__str__()

Browser other questions tagged

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