How to python raw socket ????

Grant Edwards grante at visi.com
Wed Oct 20 16:56:09 CEST 2004


On 2004-10-15, Leon <square690410 at yahoo.com.tw> wrote:

It's not good form to rely on the subject of the message to ask
your question.  Repeat the question in the body of the message:

   <http://www.catb.org/~esr/faqs/smart-questions.html>

> have any relate module ??

Not that I'm aware of.

> or write example ??

Here's a raw socket demo that sends and receives raw Ethernet
packets using protocol number 0x55aa on interface eth1.  The
file is available at <ftp://ftp.visi.com/users/grante/python/rawDemo.py>.

Last time I looked, the socket module supported raw sockets
under Linux only.

---------------------------------8<---------------------------------
#!/usr/bin/python

import sys
import string
import struct
from socket import *

proto = 0x55aa

s = socket(AF_PACKET, SOCK_RAW, proto)
s.bind(("eth1",proto))

ifName,ifProto,pktType,hwType,hwAddr = s.getsockname()

srcAddr = hwAddr
dstAddr = "\x01\x02\x03\x04\x05\x06"
ethData = "here is some data for an ethernet packet"

txFrame = struct.pack("!6s6sh",dstAddr,srcAddr,proto) + ethData

print "Tx[%d]: "%len(ethData) + string.join(["%02x"%ord(b) for b in ethData]," ")
		      
s.send(txFrame)

rxFrame = s.recv(2048)

dstAddr,srcAddr,proto = struct.unpack("!6s6sh",rxFrame[:14])
ethData = rxFrame[14:]

print "Rx[%d]: "%len(ethData) + string.join(["%02x"%ord(b) for b in ethData]," ")

s.close()
---------------------------------8<---------------------------------



-- 
Grant Edwards                   grante             Yow!  ... I want to perform
                                  at               cranial activities with
                               visi.com            Tuesday Weld!!



More information about the Python-list mailing list