I'm a programming noob following a python video tutorial to create a packet sniffer and it makes use of socket.AF_PACKET
, but my system doesn't have this. I'm guessing it's because of a different operating system. Is there any simple workaround for this? Here's my code with AF_PACKET on the first line of main
:
import socket
import struct
import textwrap
def main():
conn = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))
while True:
raw_data, addr = conn.recvfrom(65536) # biggest buffer size
dest_mac, src_mac, eth_proto, data = ethernet_frame(raw_data)
print('\nEthernet Frame: ')
print('Destination: {}, Source: {}, Protocol: {}'.format(dest_mac, src_mac, eth_proto))
# Unpack ethernet frame
def ethernet_frame(data): # pass packets into this function
dest_mac, src_mac, proto = struct.unpack('! 6s 6s H', data[:14])
return get_mac_addr(dest_mac), get_mac_addr(src_mac), socket.htons(proto), data[14:] #htons is endian bit compatibility
# Return properly formatted MAC address (ie AA:BB:CC:DD:EE:FF)
def get_mac_addr(bytes_addr):
bytes_str = map('{:02x}'.format, bytes_addr) # 2 decimal places
return ':'.join(bytes_str).upper() # mac addr
main()