How can I sort out all the  domain range from 192.55.22.0 to 192.56.22.0  through python
I want to perform a set of network tasks on an IP address range. As soon as the range is getting bigger, I fail to enumerate all hosts in the range. I want to be able to iterate through all hosts of a network with the net mask 
If I pass any range from one to another to show between the range
            Asked
            
        
        
            Active
            
        
            Viewed 245 times
        
    1
            
            
        - 
                    this library may help you - http://pypi.python.org/pypi/ipcalc/0.1 as may this question http://stackoverflow.com/questions/819355/how-can-i-check-if-an-ip-is-in-a-network-in-python – Rich Jun 11 '11 at 11:03
 
2 Answers
4
            
            
        Your example is a bit confusing. What is between "192.55.22.0" and "192.56.22.0"? You wrote "iterate through all hosts of a network with the net mask", but that range is not one complete network.
In a general case, to iterate from some ip to another, you can use:
def ip_atoi(ip):
    return struct.unpack('!I', socket.inet_aton(ip))[0]
def ip_itoa(ip):
    return socket.inet_ntoa(struct.pack('!I', ip))
current = ip_atoi('192.55.22.0')
end = ip_atoi('192.56.22.0')
for ip in xrange(current, end):
    do_something_on(ip_itoa(ip))
If you have problems in performing the network operations quickly on so many hosts, have a look at Pool in the multiprocessing module. It might speed up your operations by processing a couple of hosts at once.
        viraptor
        
- 33,322
 - 10
 - 107
 - 191
 
3
            
            
        With pure Python (and IPv6 support):
import socket,struct
# In Python 3+, you can simply use range
# In Python 2, you can substitute xrange if you're only dealing with IPv4
def _range(a, b):
    while a<b:
        yield a
        a+=1
def addrRange(start,end,fam=socket.AF_INET):
    famFmt = '!I' if fam == socket.AF_INET else '!Q'
    addr2int = lambda a: struct.unpack(famFmt, socket.inet_pton(fam, a))[0]
    for ai in _range(addr2int(start), addr2int(end)+1):
        yield socket.inet_ntop(fam, struct.pack(famFmt, ai))
for a in addrRange('192.55.22.0', '192.56.22.0'):
    print(a) # Or do something with the address
        phihag
        
- 278,196
 - 72
 - 453
 - 469