使用Jpcap监听网卡,捕获数据包

使用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 }

 

以后再来完善吧...

 

 

 

转载于:https://www.cnblogs.com/wolves-dave/archive/2013/01/18/2866173.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值