Java如何处理ICMP报文的收发

欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入

前言

java是跨平台语言,一般来说对网络的操作都在IP层以上,也就是只能对tcp/udp进行操作,当然也可以设置部分tcp/udp的option,如果想再往IP层或者数据link层操作就无能为力了,必须依靠jni使用本地OS的socket部分接口。很幸运,我在知道有winpcap的时候同时也知道有人在开发jpcap,此包可以方便的操作网络底层应用协议,以下详细描述。

实施步骤

下载需要的包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工具所产生的网络行为。以下为代码详细。

    importjava.net.InetAddress; importjpcap.JpcapCaptor; importjpcap.JpcapSender; importjpcap.NetworkInterface; importjpcap.packet.EthernetPacket; importjpcap.packet.ICMPPacket; importjpcap.packet.IPPacket; classICMP { publicstaticvoidmain(String[]args)throwsjava.io.IOException{ NetworkInterface[]devices=JpcapCaptor.getDeviceList(); if(args.length<1){ System.out.println(“Usage:javaICMP<deviceindex(e.g.,0,1..)>”); for(inti=0;i<devices.length;i++) System.out.println(i+”:”+devices[i].name+”(“+devices[i].description+”)”); System.exit(0); } intindex=Integer.parseInt(args[0]); //开启网络设备 JpcapCaptorcaptor=JpcapCaptor.openDevice(devices[index],2000,false,3000); //设置只过滤icmp包 captor.setFilter(“icmp”,true); JpcapSendersender=captor.getJpcapSenderInstance(); ICMPPacketp=newICMPPacket(); 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(); EthernetPacketether=newEthernetPacket(); ether.frametype=EthernetPacket.ETHERTYPE_IP; //填写自己和对方的mac地址,必须要正确填写,如果有错误将无法收到回包 ether.dst_mac=newbyte[]{(byte)0x00,(byte)0x03,(byte)0x2d,(byte)0x02,(byte)0xd1,(byte)0x69}; ether.src_mac=newbyte[]{(byte)0x08,(byte)0x00,(byte)0x46,(byte)0xad,(byte)0x3c,(byte)0x12}; p.datalink=ether; sender.sendPacket(p); System.out.println(“send…”); ICMPPacketrp=null; while(true){ rp=(ICMPPacket)captor.getPacket(); if(rp==null){ thrownewIllegalArgumentException(“norcvicmpechoreply”); }else { System.out.println(“rcvicmpechoreply”); return; } } } }
人要有梦想,有了梦想才会努力奋斗,

Java如何处理ICMP报文的收发

相关文章:

你感兴趣的文章:

标签云: