1
0

IPTools.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # The contents of this file are subject to the Python Software Foundation
  2. # License Version 2.3 (the License). You may not copy or use this file, in
  3. # either source code or executable form, except in compliance with the License.
  4. # You may obtain a copy of the License at http://www.python.org/license.
  5. #
  6. # Software distributed under the License is distributed on an AS IS basis,
  7. # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  8. # for the specific language governing rights and limitations under the
  9. # License.
  10. from struct import pack, unpack
  11. from socket import inet_aton, inet_ntoa
  12. def compact(ip, port):
  13. return pack("!4sH", inet_aton(ip), port) # ! == "network order"
  14. # 4s == "4-byte string."
  15. # H == "unsigned short"
  16. def uncompact(x):
  17. ip, port = unpack("!4sH", x)
  18. return inet_ntoa(ip), port
  19. def uncompact_sequence(b):
  20. for x in xrange(0, len(b), 6):
  21. ip, port = uncompact(b[x:x+6])
  22. port = int(port)
  23. yield (ip, port)
  24. def compact_sequence(s):
  25. b = []
  26. for addr in s:
  27. c = compact(addr[0], addr[1])
  28. b.append(c)
  29. return ''.join(b)
  30. ##import ctypes
  31. ##class CompactAddr(ctypes.Structure):
  32. ## _fields_ = [('ip', ctypes.c_int32),
  33. ## ('port', ctypes.c_int16)]
  34. ##
  35. ##def compact_sequence_c(s):
  36. ## b = ctypes.create_string_buffer(6 * len(s))
  37. ## a = ctypes.addressof(b)
  38. ## for i, addr in enumerate(s):
  39. ## c = compact(addr[0], addr[1])
  40. ## ctypes.cast(
  41. ## offset = i*6
  42. ## b[offset:offset + 6] = c
  43. ## return b