Skip to content

Instantly share code, notes, and snippets.

@Paulius11
Last active February 15, 2023 09:35
Show Gist options
  • Save Paulius11/a49d9c8443d7477bb546f85c4a098d9f to your computer and use it in GitHub Desktop.
Save Paulius11/a49d9c8443d7477bb546f85c4a098d9f to your computer and use it in GitHub Desktop.
Parse ICMP packet with sockets
import socket
import struct
# create a raw socket that listens for ICMP packets
icmp = socket.getprotobyname('icmp')
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
while True:
packet, address = sock.recvfrom(1024)
print(len(packet))
# parse the IP header to determine the protocol
ip_header = packet[:20]
iph = struct.unpack('!BBHHHBBH4s4s', ip_header)
version = iph[0] >> 4 # Shifts bit similar to slicing, it means get first 4 bits
ihl = iph[0] & 0xF # This means get last 4 bits from iph[0] octet
protocol = iph[6]
if protocol == socket.IPPROTO_ICMP:
# unpack the ICMP header fields
icmp_header = packet[20:28]
icmp_type, code, checksum, packet_id, sequence = struct.unpack('!BBHHH', icmp_header)
# print the ICMP packet information
print(f'Received ICMP packet from {address}:')
print(f' Type: {icmp_type}')
print(f' Code: {code}')
print(f' Checksum: {checksum}')
print(f' Packet ID: {packet_id}')
print(f' Sequence: {sequence}')
print()
# unpack the ICMP header fields
icmp_type, code, checksum, packet_id, sequence = struct.unpack('!BBHHH', packet[20:28])
# print the ICMP packet information
print(f'Received ICMP packet from {address}:')
print(f' Type: {icmp_type}')
print(f' Code: {code}')
print(f' Checksum: {checksum}')
print(f' Packet ID: {packet_id}')
print(f' Sequence: {sequence}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment