import jpcap.JpcapCaptor;import jpcap.NetworkInterface;import jpcap.NetworkInterfaceAddress;public class TCPCollection { public static void main(String[] args){ NetworkInterface[] devices = JpcapCaptor.getDeviceList();//獲取網絡接口列表 for(int i = 0; i < devices.length; i++){ //名稱、描述 System.out.println(i + ":" + devices[i].name + "(" + devices[i].description + ")"); //數據鏈路層名稱、描述 System.out.println("datalink:" + devices[i].datalink_name + "(" + devices[i].datalink_description + ")"); //MAC地址 System.out.print(" MAC address:"); for(byte b: devices[i].mac_address){ System.out.print(Integer.toHexString(b & 0xff) + ":"); } System.out.println(); //IP地址、子網掩碼、廣播地址 for(NetworkInterfaceAddress a : devices[i].addresses){ System.out.println(" address: " + a.address + "|" + a.subnet + "|" + a.broadcast); } } } }
public static void main(String[] args){ NetworkInterface[] devices = JpcapCaptor.getDeviceList();//獲取網絡接口列表 int index = 0; try { JpcapCaptor captor = JpcapCaptor.openDevice(devices[index], 65535, false, 20); } catch (IOException e) { e.printStackTrace(); System.out.println("抓取數據包時出現異常!!!"); }}
名稱 目的
NetworkInterderface 要打開的網絡接口。
intrface
int snaplen 一次捕獲數據包的最大byte數。
boolean prommics 是否採用混亂模式
混亂模式中,能夠捕獲全部數據包,即使源MAC或目的MAC地址與打開的網絡接口的MAC地址不相同。this 而非混亂模式中只能捕獲由宿主機發送和接收的數據包。
int to_ms 捕獲的數據包的超時設置(數量級爲毫秒)。
|
class PacketPrinter implements PacketReceiver { //this method is called every time Jpcap captures a packet public void receivePacket(Packet packet){ System.out.print(packet); }}
JpcapCaptor captor = JpcapCaptor.openDevice(devices[index], 65535, false, 20);captor.processPacket(2, new PacketPrinter());captor.close();
JpcapCaptor captor = JpcapCaptor.openDevice(devices[index], 65535, false, 20); for(int i=0; i<10; i++){ System.out.println(i + ":" + captor.getPacket()); } captor.close();
JpcapCaptor captor = JpcapCaptor.openDevice(devices[index], 65535, false, 20); captor.setFilter("ip and tcp", true);
JpcapCaptor captor = JpcapCaptor.openDevice(devices[index], 65535, false, 20); JpcapWriter writer = JpcapWriter.openDumpFile(captor, "yourfilename");
for(int i=0; i<10; i++){ Packet packet = captor.getPacket(); writer.writePacket(packet); } writer.close();