2016-07-16 34 views
3

我正在使用Python構建一個數據包嗅探程序,但是我碰到了一個減速帶。出於某種原因,我認爲套接字沒有正確導入,因爲我在運行程序時收到以下消息:AttributeError: module 'socket' has no attribute 'AF_PACKET'AttributeError:模塊'套接字'沒有屬性'AF_PACKET'

我使用的是OS X,而Pycharm是我的IDE,我運行的是最新版本的Python幫助。

反正這是我的完整的程序至今:

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

感謝提前任何幫助!

+0

Bucky Roberts。新波士頓 – Dimensionless

回答

5

實際上,AF_PACKET在OS X上不起作用,它在Linux上工作。

AF_PACKET equivalent under Mac OS X (Darwin)

+0

所以你說我必須繼續在Linux機器上開發? –

+0

'(socket.AF_INET,socket.SOCK_RAW,socket.IPPROTO_IP)'工作嗎? –

+0

您可以在VirtualBox上運行Linux。實際上,我不知道這些套接字協議家族是否可以在OS X上工作。您可以試試! – Jing

相關問題