Generator to iterate over an interval of IPs


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. import socket, struct
  2.  
  3. def inet_range(start, stop):
  4.  
  5. """Generator to iterate over an interval of IPs.
  6. start & stop should be IPs as string, e.g. '127.0.0.1'.
  7. """
  8.  
  9. lstart, = struct.unpack('>L', socket.inet_aton(start))
  10. lstop, = struct.unpack('>L', socket.inet_aton(stop))
  11. inc = 0
  12. while inc <= (lstop - lstart):
  13. lcur = lstart + inc
  14. inc += 1
  15. yield socket.inet_ntoa(struct.pack('>L', lcur))

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.