服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

java如何处理arp报文的收发


  前言

  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中,否则无法编译通过,以下为代码详细。

import java.net.inet4address;
import java.net.inetaddress;
import java.util.arrays;

import jpcap.*;
import jpcap.packet.*;

public class arp {
 public static byte[] arp(inetaddress ip) throws java.io.ioexception{
  //发现本机器的网络接口
  int i;
  networkinterface[] devices=jpcapcaptor.getdevicelist();
  networkinterface device=null;
  for (i = 0; i < devices.length; i++)
  {
   system.out.println(devices[i].description);
  }
  device = devices[2];//我的机器是第三个进行网络通信

  if(device==null)
   throw new illegalargumentexception(ip+" is not a local address");

  //开启网络接口
  jpcapcaptor captor=jpcapcaptor.opendevice(device,2000,false,3000);
  captor.setfilter("arp",true);
  jpcapsender sender=captor.getjpcapsenderinstance();

  inetaddress srcip=null;
  //获得接口地址,这里考虑到一网络接口可能有多地址
  for(i = 0; i < device.addresses.length ; i++)
   if(device.addresses[i].address instanceof inet4address){
    srcip=device.addresses[i].address;
    break;
  }

  //填写全1广播mac目标地址
  byte[] broadcast=new byte[]{(byte)255,(byte)255,(byte)255,(byte)255,(byte)255,(byte)255};
  arppacket arp=new arppacket();
  arp.hardtype=arppacket.hardtype_ether;
  arp.prototype=arppacket.prototype_ip;
  arp.operation=arppacket.arp_request;
  arp.hlen=6;
  arp.plen=4;
  arp.sender_hardaddr=device.mac_address;
  arp.sender_protoaddr=srcip.getaddress();
  arp.target_hardaddr=broadcast;
  arp.target_protoaddr=ip.getaddress();

  ethernetpacket ether=new ethernetpacket();
  ether.frametype=ethernetpacket.ethertype_arp;
  ether.src_mac=device.mac_address;
  ether.dst_mac=broadcast;
  arp.datalink=ether;
  //发送
  sender.sendpacket(arp);
  //处理回复
  while(true){
   arppacket p=(arppacket)captor.getpacket();
   if(p==null){
    throw new illegalargumentexception(ip+" is not a local address");
   }
   if(arrays.equals(p.target_protoaddr,srcip.getaddress())){
    return p.sender_hardaddr;
   }
  }
 }

 public static void main(string[] args) throws exception{
  int i;
  if(args.length<1){
   system.out.println("usage: java arp <ip address>");
  }else{
   byte[] mac=arp.arp(inetaddress.getbyname(args[0]));
   for (i = 0;i < mac.length; i++)
    system.out.print(integer.tohexstring(mac[i]&0xff) + ":");
   system.out.println();
   system.exit(0);
  }
 }
}

  运行:java arp <ipaddr>

  本程序经过测试,在linux和win都可以正常运行。

扫描关注微信公众号