xipv4.py 639 B

1234567891011121314151617181920212223242526
  1. # update: 2021-6-21-16
  2. def int_to_ip(integer):
  3. """
  4. 整型转ip
  5. """
  6. raw = bin(int(integer)).lstrip('0b').zfill(32)
  7. return '%d.%d.%d.%d' % (int(raw[0:8], 2), int(raw[8:16], 2), int(raw[16:24], 2), int(raw[24:32], 2))
  8. def ip_to_int(ip):
  9. """
  10. ip转整型
  11. """
  12. if not ip:
  13. return 0
  14. ip = str(ip)
  15. raw = ip.split('.')
  16. if len(raw) != 4:
  17. return 0
  18. binnum = bin(int(raw[0])).lstrip('0b').zfill(8)
  19. binnum += bin(int(raw[1])).lstrip('0b').zfill(8)
  20. binnum += bin(int(raw[2])).lstrip('0b').zfill(8)
  21. binnum += bin(int(raw[3])).lstrip('0b').zfill(8)
  22. return int(binnum, 2)