Skip to content

Instantly share code, notes, and snippets.

@changtimwu
Created January 9, 2012 09:58
Show Gist options
  • Select an option

  • Save changtimwu/1582268 to your computer and use it in GitHub Desktop.

Select an option

Save changtimwu/1582268 to your computer and use it in GitHub Desktop.
packet buffer binary processing
#global process require exports
sys = require 'util'
pcap = require 'pcap'
require 'buffertools'
if process.argv.length > 4
sys.error "usage: simple_capture interface filter"
sys.error "Examples: "
sys.error ' simple_capture "" "tcp port 80"'
sys.error ' simple_capture eth1 ""'
sys.error ' simple_capture lo0 "ip proto \\tcp and tcp port 80"'
process.exit(1)
hwif = process.argv[2]
filter = process.argv[3]
pcap_session = pcap.createSession hwif, filter
# libpcap's internal version numnber
sys.puts pcap.lib_version
# Print all devices, currently listening device prefixed with an asterisk
pcap_session.findalldevs().forEach (dev)->
if pcap_session.device_name == dev.name
sys.print "* "
sys.print dev.name+" "
if dev.addresses.length > 0
dev.addresses.forEach (address)->
sys.print address.addr+"/"+address.netmask
sys.print "\n"
else
sys.print "no address\n"
Binary = require 'binary'
is_spt_pkt = ( dmacbuf) ->
prefix = new Buffer [ 0x01, 0x80, 0xc2 ]
return dmacbuf.slice(0,3).equals(prefix)
decode_etherpkt = (pktbuf) ->
Binary.parse(pktbuf).buffer('dmac', 6).buffer('smac',6).buffer('etype', 2).vars
decode_etherpkt2 = (pktbuf) ->
dmacbuf = pktbuf.slice( 0,6)
smacbuf = pktbuf.slice( 6,12)
return { dmac: dmacbuf.toHex(), smac: smacbuf.toHex()}
# Listen for packets, decode them, and feed the simple printer. No tricks.
pcap_session.on 'packet', (raw_packet)->
#packet = pcap.decode.packet raw_packet
#console.log 'dmac:', packet.link.dhost
#console.log 'smac:', packet.link.shost
#console.log 'etype:',packet.link.ethertype
#sys.puts pcap.print.packet(packet)
packet = decode_etherpkt raw_packet
console.log packet
if is_spt_pkt( packet.dmac)
console.log 'got spanning tree'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment