allexj allexj - 3 months ago 30
Python Question

Send scapy packets through raw sockets in python

Is it possible? If yes? How?

This is my script (it doesn't work):

from scapy.all import *
import socket

try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
p=IP(dst="192.168.1.254")/TCP(flags="S", sport=RandShort(), dport=80)
s.connect(("192.168.1.254",80))
s.send(p)
print ("Request sent!")
except:
print ("An error occurred.")

Answer

To send a scapy packet using raw sockets you have to convert your packet to raw bytes first. For example a packet crafted using scapy like this:

p = IP(dst="192.168.1.254")/TCP(flags="S", sport=RandShort(),dport=80)

should be converted to raw bytes with bytes(p). This will give you something like:

'E\x00\x00(\x00\x01\x00\x00@\x06\xf6w\xc0\xa8\x01\t\xc0\xa8\x01\xfe\x97%\x00P\x00\x00\x00\x00\x00\x00\x00\x00P\x02 \x00t\x15\x00\x00'

Then you can send it using raw sockets. So for your example you could modify a little your code like:

from scapy.all import *
import socket

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    p = IP(dst="192.168.1.254")/TCP(flags="S", sport=RandShort(),dport=80)
    s.connect(("192.168.1.254",80))
    s.send(bytes(p))
    print "[+] Request Sent!"
except Exception, e:
    raise e

This should work!