9

I am working on building a packet sniffing program using Python, however I have hit a speed bump. For some reason I think socket has not imported properly, because I am getting the following message when my program is run: AttributeError: module 'socket' has no attribute 'AF_PACKET'

I am using OS X and Pycharm is my IDE and I am running the latest version of Python if that helps.

Anyways here is my complete program so far:

import struct
import textwrap
import socket

def main():
    connection = socket.socket(socket.AF_PACKET, socket.SOCKET_RAW, socket.ntohs(3))

    while True:
        rawData, address = connection.recvfrom(65535)
        reciever_mac, sender_mac, ethernetProtocol, data = ethernet_frame(rawData)
        print('\nEthernet Frame: ')
        print('Destination: {}, Source: {}, Protocol: {}'.format(reciever_mac, sender_mac, ethernetProtocol))

# Unpack ethernet frame
def ethernet_frame(data):
    reciever_mac, sender_mac, protocol = struct.unpack('! 6s 6s H', data[:14])
    return getMacAddress(reciever_mac), getMacAddress(sender_mac), socket.htons(socket), data[14:]

# Convert the Mac address from the jumbled up form from above into human readable format
def getMacAddress(bytesAddress):
    bytesString = map('{:02x}'.format, bytesAddress)
    macAddress = ':'.join(bytesString).upper()
    return macAddress

main()

Thanks for any help in advance!

1
  • 5
    Bucky Roberts. The New Boston
    – Deiknymi
    Commented Mar 12, 2017 at 6:25

2 Answers 2

11

Actually, AF_PACKET doesn't work on OS X, it works on Linux.

AF_PACKET equivalent under Mac OS X (Darwin)

5
  • So you're saying I must continue my development on a Linux machine? Commented Jul 16, 2016 at 1:18
  • Would (socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP) work? Commented Jul 16, 2016 at 1:34
  • You can run Linux on VirtualBox. Actualy i don't know exact whether these socket protocol families work on OS X. You can try it!
    – Jing
    Commented Jul 16, 2016 at 2:43
  • 2
    Well that explains why it doesn't work, though I'd much prefer an exception than literal code not being available on a platform
    – Allison
    Commented Nov 18, 2017 at 1:23
  • What is the equivalent on windows?
    – X0-user-0X
    Commented Jun 14, 2022 at 14:38
0

I ran into this issue on macOS 10.13.1, using Python 3.6.3 and this cool scapy fork that is compatible with python3.

I was using version 0.22 of that tool and as suggested in this issue downgrading to version 0.21 fixed this issue!

In case scapy is not a viable alternative, you could also try the pcap library as suggested in this post (although using python 2 seems to be necessary here).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.