前面已经介绍过,Jpcap是为JAVA编写的类包,提供很多类和接口,能够获得IP数据包。详情请见:
http://blog.csdn.net/arui319/archive/2005/06/02/386678.aspx
下面是使用的例子代码
import jpcap.*;
class getMessage implements JpcapHandler
{
public void handlePacket(Packet packet)
{
if (packet instanceof TCPPacket) //TCPPacket还是UDPPacket?
{
TCPPacket tcpPacket = (TCPPacket)packet;
if ( tcpPacket.dst_port == 3000)//监听端口3000
{
System.out.println(new String(tcpPacket.data)); //输出数据
}
}
}
public static void main(String[] args)
{
try
{
String[] lists = Jpcap.getDeviceDescription();
//这里需要根据自己机器的情况判断网卡是第几个硬件
System.out.println("Start capturing on " + lists[2]);
//循环获取网络数据包
Jpcap jpcap1 =
Jpcap.openDevice(Jpcap.getDeviceList()[2], 10000, false, 20);
jpcap1.loopPacket(-1, new getMessage());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}