Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python raw socket receive issue

I am using the following python script for raw socket packet transfer. Packet transfer is fine, but I am not able to print the incoming packet from the other end.

from socket import socket, AF_PACKET, SOCK_RAW

s = socket(AF_PACKET, SOCK_RAW)
s.bind(("eth0", 0))
src_addr = "\x54\xbe\xf7\x40\xf5\x82"
dst_addr = "\xff\xff\xff\xff\xff\xff"

payload = ("[("*30)+"Hello"+("]"*30)
checksum = "\x1a\x2b\x3c\x4d"

data = payload+checksum

s.send(dst_addr+src_addr+data)

#for receive function 

response=s.recv(4096)
print response
s.close()
like image 467
Balaji subramanian Avatar asked Oct 13 '25 10:10

Balaji subramanian


1 Answers

There is a third argument to the socket function: protocol. If not given, it's defaulting to 0. For AF_PACKET / SOCK_RAW, the protocol argument specifies what kind of packets you're interested in receiving. The values are documented in the packet(7) man page: http://man7.org/linux/man-pages/man7/packet.7.html

I don't think the values are actually defined anywhere in the core python2 modules. Some of them can be found in scapy (http://www.secdev.org/projects/scapy/), or you can just hunt up the linux header file where they are defined (/usr/include/linux/if_ether.h).

So, to fix this, change your code to:

from socket import socket, AF_PACKET, SOCK_RAW, htons

ETH_P_ALL = 3
ETH_P_IP = 0x800   # Alternatively using this will receive the next IP packet
s = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL))
...

Other comments on your code:

As written, the packet you're sending is unlikely to be comprehensible by anyone. You've got a dst and src MAC address, but then you're not providing an EtherType. Instead the first "[(" will be seen as the EtherType. That probably won't make sense to any receiver of the packet so it will just be discarded.

Also, you should understand that with a raw socket, you're going to receive the next packet of the type you've specified in the protocol. That isn't necessarily (and in fact probably won't be) a response to the packet you just sent.

like image 56
Gil Hamilton Avatar answered Oct 15 '25 10:10

Gil Hamilton