I get an OSError from Python when I use ntohs(0x0003)
as the protocol argument for a SOCK_RAW socket on Ubuntu.
File "sniffer_all.py", line 44, in main
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.ntohs(0x0003))
File "/usr/lib/python3.5/socket.py", line 134, in __init__
_socket.socket.__init__(self, family, type, proto, fileno)
OSError: [Errno 22] Invalid argument
I checked the /etc/protocols file, and it lists 3 as the GGP :
...
ggp 3 GGP # gateway-gateway protocol
I do not know why this error occurs if the protocol is configured. I am running python with sudo, so I should have no access issues.
Replacing socket.ntohs(0x0003)
with another protocol, such as socket.IPPROTO_UDP
, fixes the error, but limits which traffic the socket can handle.
First of all, sudo
or root is required if you want to use raw sockets, but you are calling socket()
incorrectly. socket()
takes arguments in host byte order but by calling ntohs()
you convert the 8 bit GGP protocol value of 3
to the 16 bit value 768
which is wrong because the maximum possible protocol value is 255
.
You can either do it like this
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, 3)
or in a more readable way
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname('ggp'))