Ahad Sheriff
Ahad Sheriff

Reputation: 1829

AttributeError: module 'socket' has no attribute 'AF_PACKET'

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!

Upvotes: 9

Views: 22337

Answers (2)

Robbotnik
Robbotnik

Reputation: 545

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).

Upvotes: 0

Jing
Jing

Reputation: 1130

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

AF_PACKET equivalent under Mac OS X (Darwin)

Upvotes: 11

Related Questions