nw_cap.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import socket
  2. import textwrap
  3. import eth
  4. import ip
  5. import transport
  6. def multi_line(prefix, string, size=80):
  7. size -= len(prefix)
  8. if isinstance(string, bytes):
  9. string = ''.join(r'\x{:02x}'.format(byte) for byte in string)
  10. if size % 2:
  11. size -= 1
  12. return '\n'.join([prefix + line for line in textwrap.wrap(string, size)])
  13. TAB1 = "\t"
  14. TAB2 = "\t\t"
  15. TAB3 = "\t\t\t"
  16. conn = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))
  17. if __name__ == "__main__":
  18. while True:
  19. raw_data, addr = conn.recvfrom(65535)
  20. dest_mac, src_mac, eth_proto, data = eth.ethernet_unpack(raw_data)
  21. version, header_len, tos, total_len, identification, x_bit, DFF, MFF, frag_offset, TTL, proto, header_checksum , s_ip, d_ip, data = ip.ip_unpack(data)
  22. print("Ethernet Frame")
  23. print(TAB1 + "- Destination Mac : {} , Source Mac : {} , Protocol : {}" .format(str(dest_mac), str(src_mac), str(eth_proto)))
  24. print(TAB1 + "- IPv4 Packet")
  25. print("""{}-Version : {}, Header Length : {}, TOS : {}, Total Length : {}
  26. {}- ID : {}, Flags : {}|{}|{}, Fragment Offset : {}, TTL : {}
  27. {}- Protocol : {}, Checksum : {}, Source IP : {}, Destination IP : {}""" .format(TAB2, str(version), str(header_len), str(tos), str(total_len), TAB2, str(identification), str(x_bit), str(DFF), str(MFF), str(frag_offset), str(TTL), TAB2, str(proto), str(header_checksum), str(s_ip), str(d_ip) ))
  28. if str(proto) == "1":
  29. icmp_type, icmp_code, icmp_checksum, data = ip.icmp_unpack(data)
  30. print(TAB2 + "- ICMP Packet")
  31. print(TAB3 + "- Type : {}, Code : {}, Checksum : {}" .format(str(icmp_type), str(icmp_code), str(icmp_checksum)))
  32. print(TAB3 + "- Data")
  33. print(multi_line(TAB3, data))
  34. elif str(proto) == "6":
  35. s_port, d_port, seq_no, ack_no, cwr, ece, urg, ack, psh, rst, syn, fin , window, checksum, urg_pointer, data = transport.tcp_unpack(data)
  36. print(TAB2 + "- TCP Segment")
  37. print(TAB3 + """- Source Port : {}, Destination Port : {}, SEQ No : {}, ACK No : {}
  38. {}- Flags : {}|{}|{}|{}|{}|{}|{}|{}
  39. {}- Window : {}, Checksum : {}, URG Pointer : {}""" .format( str(s_port), str(d_port), str(seq_no), str(ack_no), TAB3, str(cwr), str(ece), str(urg), str(ack), str(psh), str(rst), str(syn), str(fin), TAB3, str(window), str(checksum), str(urg_pointer) ))
  40. print(TAB2 + "- Data")
  41. print(multi_line(TAB3, data))
  42. elif str(proto) == "17":
  43. s_port, d_port, length, checksum, data = transport.udp_unpack(data)
  44. print(TAB2 + "- UDP Datagram")
  45. print(TAB3 + "- Source Port : {}, Destination Port : {}, Length : {}, Checksum : {}" .format(str(s_port), str(d_port), str(length), str(checksum)))
  46. print(TAB3 + "- Data")
  47. print(multi_line(TAB3, data))