Skip to content

Instantly share code, notes, and snippets.

@picatz
Created November 5, 2017 00:53
Show Gist options
  • Save picatz/b0816dc6f52d69bab943f052edac30fc to your computer and use it in GitHub Desktop.
Save picatz/b0816dc6f52d69bab943f052edac30fc to your computer and use it in GitHub Desktop.
Crystal LibPcap
@[Link("pcap")]
lib LibPcap
# Size to use when allocating the buffer that contains the libpcap errors.
PCAP_ERRBUF_SIZE = UInt8.new(256)
# Item in a list of interfaces.
struct PcapIf
next : PcapIf* # next interface in the list
name : LibC::Char* # name to hand to pcap_open_live()
description : LibC::Char* # textual description of interface, or NULL
addresses : PcapAddr* # here for structure, not for function
flags : LibC::UInt # PCAP_IF_ interface flags
end
# Loose representation of an interface address. Not all that
# useful at the moment!
struct PcapAddr
next : PcapAddr*
addr : Void*
netmask : Void*
broadaddr : Void*
dstaddr : Void*
end
# Find the default device on which to capture.
# http://www.tcpdump.org/manpages/pcap_lookupdev.3pcap.html
#fun pcap_lookupdev : LibC::Char*
fun pcap_lookupdev(errbuf : LibC::Char* ) : LibC::Char*
# Get a list of capture devices.
# http://www.tcpdump.org/manpages/pcap_findalldevs.3pcap.html
fun pcap_findalldevs(list : PcapIf**, errbuf : LibC::Char*) : LibC::Int
# Free list of capture devices.
# http://www.tcpdump.org/manpages/pcap_findalldevs.3pcap.html
fun pcap_freealldevs(list : PcapIf*)
end
module Pcap
def self.lookupdev
err = LibPcap::PCAP_ERRBUF_SIZE.dup
String.new(LibPcap.pcap_lookupdev(pointerof(err)))
end
def self.findalldevs
err = LibPcap::PCAP_ERRBUF_SIZE.dup
result = LibPcap.pcap_findalldevs(out iface_iterator, pointerof(err))
if result == -1
raise Exception.new "Unable to find devices! #{err}"
end
interfaces = [] of LibPcap::PcapIf
orig = iface_iterator
iface = iface_iterator
until iface_iterator.null?
iface = iface_iterator.value
interfaces << iface
iface_iterator = iface.next
end
LibPcap.pcap_freealldevs(orig)
interfaces
end
end
interfaces = Pcap.findalldevs
puts String.new(interfaces.first.name) # no string, sometimes junk?!
#interfaces.each do |interface|
# name = String.new(interface.name)
# puts name
#end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment