Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion from IP string to integer, and backward in Python

i have a little problem with my script, where i need to convert ip in form 'xxx.xxx.xxx.xxx' to integer representation and go back from this form.

def iptoint(ip):     return int(socket.inet_aton(ip).encode('hex'),16)  def inttoip(ip):     return socket.inet_ntoa(hex(ip)[2:].decode('hex'))   In [65]: inttoip(iptoint('192.168.1.1')) Out[65]: '192.168.1.1'  In [66]: inttoip(iptoint('4.1.75.131')) --------------------------------------------------------------------------- error                                     Traceback (most recent call last)  /home/thc/<ipython console> in <module>()  /home/thc/<ipython console> in inttoip(ip)  error: packed IP wrong length for inet_ntoa` 

Anybody knows how to fix that?

like image 910
thc_flow Avatar asked Apr 11 '11 10:04

thc_flow


People also ask

Can you convert strings to integers in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed.

How do I turn a string into an integer?

The most Pythonic way to convert a list of strings to a list of ints is to use the list comprehension [int(x) for x in strings] . It iterates over all elements in the list and converts each list element x to an integer value using the int(x) built-in function.

What command will convert strings to integers?

In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.


2 Answers

#!/usr/bin/env python import socket import struct   def ip2int(addr):     return struct.unpack("!I", socket.inet_aton(addr))[0]   def int2ip(addr):     return socket.inet_ntoa(struct.pack("!I", addr))   print(int2ip(0xc0a80164)) # 192.168.1.100 print(ip2int('10.0.0.1')) # 167772161 
like image 161
fiorix Avatar answered Oct 17 '22 17:10

fiorix


Python 3 has ipaddress module which features very simple conversion:

int(ipaddress.IPv4Address("192.168.0.1")) str(ipaddress.IPv4Address(3232235521)) 
like image 23
markhor Avatar answered Oct 17 '22 16:10

markhor