Jerry Meng
Jerry Meng

Reputation: 1506

python raw socket: Protocol not supported

I am trying to open a raw socket with Python under linux.

My simple code:

s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
s.bind((HOST, 5454))

And I got this error:

[ERROR] Protocol not supported

By the way, I am using python 2.7.3 under linux 12.04, and I used root to run the code.

Does anyone have a clue?

Update: The solution given by dstromberg is correct. If you want the whole packet, then use his solution. However, there is another combination:

s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)

that also works.

In this case, you will receive a whole TCP packet with IP and TCP headers on it. If your use dstromberg's solution, you will also see the ethernet header. So it depends on how 'raw' you want your packet to be.

Upvotes: 11

Views: 16427

Answers (3)

dstromberg
dstromberg

Reputation: 7187

This runs without error as root:

#!/usr/local/cpython-3.3/bin/python

import socket as socket_mod

#s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
socket = socket_mod.socket(socket_mod.AF_PACKET, socket_mod.SOCK_RAW, socket_mod.IPPROTO_IP)
#socket.bind(('localhost', 5454))
socket.bind(('lo', 5454))

Upvotes: 0

ZZB
ZZB

Reputation: 285

Try socket.AF_UNIX, it can solve your problem, good luck.

Upvotes: -2

dstromberg
dstromberg

Reputation: 7187

Try socket.AF_PACKET instead of socket.AF_INET.

Upvotes: 10

Related Questions