使用Jpcap监听网卡,捕获数据包,得到mac地址,ip地址和端口号(只解析了tcp数据包):
1 import jpcap.JpcapCaptor; 2 import jpcap.NetworkInterface; 3 import jpcap.PacketReceiver; 4 import jpcap.packet.*; 5 6 public class Test { 7 public static void main(String[] args) 8 { 9 try { 10 final NetworkInterface[] devices = JpcapCaptor.getDeviceList(); 11 NetworkInterface network_interface = devices[0]; 12 JpcapCaptor captor = JpcapCaptor.openDevice(network_interface, 65535, false, 20); 13 //captor.setFilter("host 122.141.231.18", true);//filter packets from ip 14 captor.loopPacket(-1, new Receiver()); 15 //Receiver receiver = new Receiver(captor.getPacket());//just get one packet 16 } catch (Exception exception) { 17 exception.printStackTrace(); 18 System.out.println("fail to dispaly the data of network interface--" + exception); 19 } 20 } 21 } 22 23 class Receiver implements PacketReceiver { 24 public Receiver() {} 25 public Receiver(Packet packet) { receivePacket(packet); } 26 public void receivePacket(Packet packet) 27 { 28 if (packet instanceof TCPPacket) {// just analyse tcp packet 29 //output mac addresses 30 EthernetPacket ethernet_packet = (EthernetPacket)packet.datalink; 31 System.out.print("Mac address----"); 32 System.out.print("source--" + ethernet_packet.getSourceAddress()); 33 System.out.print(" "); 34 System.out.println("destination--" + ethernet_packet.getDestinationAddress()); 35 //output ip addresses 36 TCPPacket tcp_packet = (TCPPacket)packet; 37 System.out.print("ip address----"); 38 System.out.print("source--" +tcp_packet.src_ip); 39 System.out.print(" "); 40 System.out.println("destination--" + tcp_packet.dst_ip); 41 //output ports 42 System.out.print("port----"); 43 System.out.print("source--" +tcp_packet.src_port); 44 System.out.print(" "); 45 System.out.println("destination--" + tcp_packet.dst_port); 46 //output data 47 System.out.println("data----"); 48 for (int index = 0; index < tcp_packet.data.length; ++index) { 49 System.out.print((char)tcp_packet.data[index]); 50 } 51 } 52 System.out.println(); 53 } 54 }
以后再来完善吧...