前言
java中使用Pcap4J抓包
学习使用pacp4j 必须要先安装环境依赖WinPcap 或者 libPcap 根据你的使用环境选择
一、Pcap4J是什么?
为实现java抓包而封装的工具包
二、使用步骤
1.安装依赖库
Ubuntu
apt-get install libpcap-dev
CentOs
yum install libpcap-devel
Mac
brew install libpcap
Windows
choco install winpcap
2.引入项目中
Gradle
compile 'org.pcap4j:pcap4j-core:1.+'
compile 'org.pcap4j:pcap4j-packetfactory-static:1.+'
Maven
<dependency>
<groupId>org.pcap4j</groupId>
<artifactId>pcap4j-core</artifactId>
<version>[1.0, 2.0)</version>
</dependency>
<dependency>
<groupId>org.pcap4j</groupId>
<artifactId>pcap4j-packetfactory-static</artifactId>
<version>[1.0, 2.0)</version>
</dependency>
发现网络接口
InetAddress addr = InetAddress.getByName("192.168.10.100");
PcapNetworkInterface nif = Pcaps.getDevByAddress(addr);
打开Pcap处理
int snapLen = 65536;
PromiscuousMode mode = PromiscuousMode.PROMISCUOUS;
int timeout = 10;
PcapHandle handle = nif.openLive(snapLen, mode, timeout);
捕获数据包
Packet packet = handle.getNextPacketEx();
handle.close();
得到包信息
IpV4Packet ipV4Packet = packet.get(IpV4Packet.class);
Inet4Address srcAddr = ipV4Packet.getHeader().getSrcAddr();
System.out.println(srcAddr);