jcap_test

import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.Arrays;

import jpcap.JpcapCaptor;
import jpcap.JpcapSender;
import jpcap.NetworkInterface;
import jpcap.NetworkInterfaceAddress;
import jpcap.packet.ARPPacket;
import jpcap.packet.EthernetPacket;


public class Test{
public static byte[] arp(InetAddress ip) throws Exception{
//find network interface
NetworkInterface[] devices=JpcapCaptor.getDeviceList();
NetworkInterface device=null;

loop: for(NetworkInterface d:devices){
for(NetworkInterfaceAddress addr:d.addresses){
if(!(addr.address instanceof Inet4Address)) continue;
byte[] bip=ip.getAddress();
byte[] subnet=addr.subnet.getAddress();
byte[] bif=addr.address.getAddress();
for(int i=0;i<4;i++){
bip[i]=(byte)(bip[i]&subnet[i]);
bif[i]=(byte)(bif[i]&subnet[i]);
}
if(Arrays.equals(bip,bif)){
device=d;
break loop;
}
}
}

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

//open Jpcap
JpcapCaptor captor=JpcapCaptor.openDevice(device,2000,false,3000);
captor.setFilter("arp",true);
JpcapSender sender=captor.getJpcapSenderInstance();

InetAddress srcip=null;
for(NetworkInterfaceAddress addr:device.addresses)
if(addr.address instanceof Inet4Address){
srcip=addr.address;
break;
}

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) {
//args[0]="192.168.100";
//if(args.length<1){
// System.out.println("Usage: java ARP <ip address>");
//}else{
try {

byte[] mac=Test.arp(InetAddress.getByName("192.168.1.1"));
for (byte b : mac)
System.out.print(Integer.toHexString(b&0xff) + ":");
System.out.println();
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
//}
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值