'Correct method to create python raw socket

I was reading some information security and programming stuff recently and I came across raw socket. I am kind of confused for a way to create raw socket and capture the packet correctly.

Method 1

create socket with AF_INET

sock=socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.IPPROTO_*)

##IPPROTO_* can be IPPROTO_IP/IPPROTO_TCP/IPPROTO_UDP

raw_data=sock.recvfrom(65535)

But using this method I'm able to capture the packet but when i tried to decode it, I am not able to making any sense.

Method 2

sock=socket.socket(socket.AF_PACKET,socket.SOCK_RAW,socket.htons(0x0800))

raw_data=socket.recvfrom(65535)

by using second method I'm able to capture as well as decode it.

FYI, I'm trying to decode packet from ethernet lavel.

So my question is why method I is failing? and Is there anyother way to create raw socket in python.



Solution 1:[1]

If you want to create protocolless raw socket, use: socket(AF_PACKET, SOCK_RAW);

Example:

#!/usr/bin/env python
from socket import socket, AF_PACKET, SOCK_RAW
s = socket(AF_PACKET, SOCK_RAW)
s.bind(("eth1", 0))

# We're putting together an ethernet frame here, 
# but you could have anything you want instead
# Have a look at the 'struct' module for more 
# flexible packing/unpacking of binary data
# and 'binascii' for 32 bit CRC
src_addr = "\x01\x02\x03\x04\x05\x06"
dst_addr = "\x01\x02\x03\x04\x05\x06"
payload = ("["*30)+"PAYLOAD"+("]"*30)
checksum = "\x1a\x2b\x3c\x4d"
ethertype = "\x08\x01"

s.send(dst_addr+src_addr+ethertype+payload+checksum)

All credits to brice

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community