Skip to content

Instantly share code, notes, and snippets.

@FScoward
Created January 21, 2015 15:52
Show Gist options
  • Save FScoward/1b38cec9d2ea74d5e7b9 to your computer and use it in GitHub Desktop.
Save FScoward/1b38cec9d2ea74d5e7b9 to your computer and use it in GitHub Desktop.
/* sbt */
name := "packetCapture"
version := "1.0"
scalaVersion := "2.11.4"
libraryDependencies ++= Seq(
"org.pcap4j" % "pcap4j-core" % "1.3.0",
"org.pcap4j" % "pcap4j-packetfactory-static" % "1.3.0",
"net.java.dev.jna" % "jna" % "4.1.0",
"org.slf4j" % "slf4j-api" % "1.7.10",
"org.slf4j" % "slf4j-simple" % "1.7.10"
)
/* Main.scala */
import java.io.IOException
import com.sun.jna.Platform
import org.pcap4j.core.BpfProgram.BpfCompileMode
import org.pcap4j.core.{PcapStat, PacketListener, PcapHandle, PcapNetworkInterface}
import org.pcap4j.core.PcapNetworkInterface.PromiscuousMode
import org.pcap4j.packet.Packet
import org.pcap4j.util.NifSelector
/**
* Created by FScoward on 2015/01/21.
*/
object Main {
val SNAPLEN_KEY = this.getClass.getName + ".snaplen"
val SNAPLEN = Integer.getInteger(SNAPLEN_KEY, 65536)
val READ_TIMEOUT_KEY = this.getClass.getName + ".readTimeout"
val READ_TIMEOUT = Integer.getInteger(READ_TIMEOUT_KEY, 10) // [ms]
def main(args: Array[String]): Unit = {
val nif: Option[PcapNetworkInterface] = try {
Some(new NifSelector().selectNetworkInterface())
} catch {
case e: IOException => None
}
if(nif.isEmpty) System.exit(0)
println(s"${nif.get.getName}: ${nif.get.getDescription}")
val handle: PcapHandle = nif.get.openLive(SNAPLEN, PromiscuousMode.PROMISCUOUS, READ_TIMEOUT)
handle.setFilter("", BpfCompileMode.OPTIMIZE)
val packetListner = new PacketListener {
override def gotPacket(packet: Packet): Unit = {
println(packet)
}
}
val pcapDumper = handle.dumpOpen("DUMP.pcap")
try {
// 5回繰り返す
handle.loop(5, packetListner)
// handle.loop(5, pcapDumper)
} catch {
case e: InterruptedException => e.printStackTrace()
}
val ps: PcapStat = handle.getStats
println(s"ps_recv: ${ps.getNumPacketsReceived}")
println(s"ps_drop: ${ps.getNumPacketsDropped}")
println(s"ps_ifdrop: ${ps.getNumPacketsDroppedByIf}")
if(Platform.isWindows) {
println(s"bs_capt: ${ps.getNumPacketsCaptured}")
}
// 終了
handle.close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment