I'm following along with a tutorial to create a python packet sniffer and I'm getting an error using socket.py. I'm a complete noob to python and haven't been able to find anything online. Here's my code snippet:
import socket
import struct
import textwrap
def main():
conn = socket.socket(socket.AF_INET, 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()
And here's the error:
Traceback (most recent call last):
File "Untitled.py", line 26, in <module>
main()
File "Untitled.py", line 7, in main
conn = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.ntohs(3))
File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/socket.py", line 134, in __init__
_socket.socket.__init__(self, family, type, proto, fileno)
PermissionError: [Errno 1] Operation not permitted
The code originally used AF_PACKET instead of AF_INET, but I read that AF_PACKET was for Windows and AF_INET is for Linux. I'm actually on a Mac so I'm not sure if this was a correct fix. I'm using python 3.5. Any help or suggestions are greatly appreciated, thanks.
in order to use this type of socket. you need to start your script with sudo/admin rights. go to the dirctory and open terminal. then run the code with sudo rights:
sudo python3 file_name.py
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.