IP number conversion between dotnumber string and integer

Updated TrustyTony 0 Tallied Votes 815 Views Share

The need for efficient storing of IP numbers came up in discussion thread. With help of this conversion to/from the 32 bit numbers that IP numbers (the old ones) represent I could push the time of finding unique IP numbers from 10 million random numbers down to under two minutes in my Sempron 1,5 GB RAM ACER computer:

.....
9940000 254.196.90.223
9950000 255.5.230.221
9960000 255.71.96.186
9970000 255.135.189.144
9980000 255.201.68.112
1 min 40.639 s
ready, result stored in "unique_ip.txt". Push enter to quit.

Here is the functions for IP number conversion from my routine:

def ipnumber(ip):
    ip=ip.rstrip().split('.')
    ipn=0
    while ip:
        ipn=(ipn<<8)+int(ip.pop(0))
    return ipn

def ipstring(ip):
    ips=''
    for i in range(4):
        ip,n=divmod(ip,256)
        ips = str(n)+'.'+ips
    return ips[:-1] ## take out extra point



>>> ipnumber('211.234.32.123')
3555336315L
>>> ipstring(_)
'211.234.32.123'
>>>
Lardmeister 461 Posting Virtuoso

What does the _ do in ipstring(_)?

TrustyTony 888 ex-Moderator Team Colleague Featured Poster

In command line you get the last result from the last command from variable _, In my program I usually use _ to denote the return values, that I have no use for, for example when I do partition and are only interested the third part, which is after cutting:

Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)]
Type "copyright", "credits" or "license" for more information.

IPython 0.10 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object'. ?object also works, ?? prints more.

In [1]: 2+3
Out[1]: 5

In [2]: _
Out[2]: 5

In [3]: a="Heikki Kovalainen, Finnish Formula 1 driver"

In [4]: _,_,prof=a.partition(',')

In [5]: prof
Out[5]: ' Finnish Formula 1 driver'

In [6]:
Lardmeister 461 Posting Virtuoso

Doesn't look like Python at all!

TrustyTony 888 ex-Moderator Team Colleague Featured Poster

That is IPython shell, which have much extra functionality, basically can give OS commands and Python commands both.

but same is applicable Idle, Python prompt etc.

And that double was same post again, but was no way to delete it even button EDIT/DELETE.

If you want to prove IPython, you can find it in http://ipython.scipy.org/moin/Download

Or you can do

python easy_install ipython
mrkbbk 0 Newbie Poster

Hi,

You can optimize the ipnumber() function a bit with:

def ipnumber(ip):
    return reduce(lambda sum, chunk: sum <<8 | chunk, map(int, ip.split(".")))
TrustyTony 888 ex-Moderator Team Colleague Featured Poster

This one month old newbie member did clear code by his standards (as old Lisper I do get the meaning of the code you posted, but it is not idiomatic Python). This senior poster would say:

def ipnumber(ip):
    return sum(256**power*int(value) for power, value in enumerate(reversed(ip.rstrip().split('.'))))
    
def ipstring(ip):
    return '.'.join('%s' % (ip // 256**ind  % 256) for ind in reversed(range(4)))

if __name__ == '__main__':
    testcase = '211.234.32.123'
    r = ipnumber(testcase)
    print('%s = %s = %s' % (testcase, r, ipstring(r)))
mrkbbk 0 Newbie Poster

Yup, I must admit that the code snippet i cited is unreadable, and can be confusing. The reason I've decided to post it was a little provocation. You see, back then, when I was discovering beauty of Python, I saw this oneliner (although it was made to convert ethernet MAC address to long integer, not IP) and got inspired to learn reduce(), filter() and map() which are quite useful tools. Your code is much cleaner, but I just wanted to share some "ninja moves" I saw once :) Cheers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.