decode_mode5_32.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import sys
  2. import struct
  3. import csv
  4. import time
  5. IP_SRC = "081.169.252.034"
  6. def port_dst_src_to_ip(port_dst, port_src):
  7. """
  8. Convert a destination/source port to an IP addresse asuuming
  9. encoding type 5 and 32 marker value bits.
  10. """
  11. ip_1 = port_dst >> 8
  12. ip_2 = port_dst & 0xFF
  13. ip_3 = port_src >> 8
  14. ip_4 = port_src & 0xFF
  15. return "%d.%d.%d.%d" % (ip_1, ip_2, ip_3, ip_4)
  16. def decode_single(port_dst, port_src):
  17. ip = port_dst_src_to_ip(port_dst, port_src)
  18. print("port dst=%d, port src=%d, IP= %s" % (port_dst, port_src, ip))
  19. def decode_file(filename_read):
  20. filename_write = filename_read + "_decoded_ips.txt"
  21. fd_read = open(filename_read, "r")
  22. fd_write = open(filename_write, "w")
  23. fd_read.readline()
  24. csv_reader = csv.reader(fd_read, delimiter=' ')
  25. cnt = 0
  26. for val in csv_reader:
  27. if len(val) < 5:
  28. continue
  29. if cnt % 200000 == 0:
  30. print("...")
  31. cnt += 1
  32. if val[3] != IP_SRC:
  33. continue
  34. try:
  35. port_dst, port_src = int(val[5]), int(val[4])
  36. ip = port_dst_src_to_ip(port_dst, port_src)
  37. #print("%d %d -> %s" % (port_dst, port_src, ip))
  38. fd_write.write(ip +"\n")
  39. except ValueError as ex:
  40. #print(ex)
  41. # integer conversion exceptions (malformed CSV)
  42. pass
  43. #time.sleep(0.5)
  44. fd_read.close()
  45. fd_write.close()
  46. if len(sys.argv) < 2:
  47. print("usage: python script.py [single|file] [destination_port] [source_port]")
  48. sys.exit(1)
  49. if sys.argv[1] == "single":
  50. port_dst = int(sys.argv[2])
  51. port_src = int(sys.argv[3])
  52. decode_single(port_dst, port_src)
  53. else:
  54. decode_file(sys.argv[2])