一、JAVA访问ICMP
下载需要的包
http://netresearch.ics.uci.edu/kfujii/jpcap/doc/index.html上可以下到最新的jpcap,你只需要把lib中的dll文件拷贝到jre的bin目录,同时lib中的jar文件拷贝到jre中的lib/ext目录下就安装完整,当然你可以使用exe安装包进行安装,这样会更加的简单。
编码你可以使用任何你喜欢的ide工具,但是必须把jpcap.jar加到classpath中,否则无法编译通过。icmp有很多类型,当前仅用echo类型为例,也就是我们通过用的ping工具所产生的网络行为。
二、以下为详细代码。
import java.net.InetAddress;
import jpcap.JpcapCaptor;
import jpcap.JpcapSender;
import jpcap.NetworkInterface;
import jpcap.packet.EthernetPacket;
import jpcap.packet.ICMPPacket;
import jpcap.packet.IPPacket;
class ICMP
{
public static void main(String[] args) throws java.io.IOException{
NetworkInterface[] devices = JpcapCaptor.getDeviceList();
if(args.length<1){
System.out.println("Usage: java ICMP <device index (e.g., 0, 1..)>");
for(int i=0;i<devices.length;i++)
System.out.println(i+":"+devices[i].name+"("+devices[i].description+")");
System.exit(0);
}
int index=Integer.parseInt(args[0]);
//开启网络设备
JpcapCaptor captor=JpcapCaptor.openDevice(devices[index],2000,false,3000);
//设置只过滤 icmp包
captor.setFilter("icmp",true);
JpcapSender sender=captor.getJpcapSenderInstance();
ICMPPacket p=new ICMPPacket();
p.type=ICMPPacket.ICMP_ECHO;
p.seq=(short)0x0005;
p.id=(short)0x0006;
p.setIPv4Parameter(0,false,false,false,0,false,false,false,0,1010101,100,IPPacket.IPPROTO_ICMP,
InetAddress.getByName("192.168.1.30"),InetAddress.getByName("192.168.1.1"));
p.data="abcdefghijklmnopqrstuvwabcdehghi".getBytes();
EthernetPacket ether=new EthernetPacket();
ether.frametype=EthernetPacket.ETHERTYPE_IP;
//填写自己和对方的mac地址,必须要正确填写,如果有错误将无法收到回包
ether.dst_mac=new byte[]{(byte)0x00,(byte)0x03,(byte)0x2d,(byte)0x02,(byte)0xd1,(byte)0x69};
ether.src_mac=new byte[]{(byte)0x08,(byte)0x00,(byte)0x46,(byte)0xad,(byte)0x3c,(byte)0x12};
p.datalink=ether;
sender.sendPacket(p);
System.out.println("send...");
ICMPPacket rp= null;
while(true){
rp=(ICMPPacket)captor.getPacket();
if(rp==null){
throw new IllegalArgumentException("no rcv icmp echo reply");
}else
{
System.out.println("rcv icmp echo reply");
return ;
}
}
}
}
三、JAVA与Raw Socket的关系
JAVA仅支持到应用层,是无法直接操作底层的,所以JAVA如果想操作RAW SOCKET需要借助JNI调用C++/C才可以实现数捕获