1. 程式人生 > >乙太網傳送自定義協議資料包java

乙太網傳送自定義協議資料包java

        //1列舉網絡卡並開啟裝置
  jpcap.NetworkInterface[] devices = JpcapCaptor.getDeviceList();
  NetworkInterface device = devices[2];
  JpcapSender sender = null;
  //2.原始型別資料包,這種包沒有首部位元組。UDPPacket、IPPacket有首部位元組
        //需要設定udp.setIPv4Parameter(0,false,false,false,0,false,false,false,0,0,255,
        //   230,//230未定義協議
        //   InetAddress.getByName("192.168.1.100"), 
        //   InetAddress.getByName("192.168.1.102"));
  Packet udp = new Packet();
  try {
      sender = JpcapSender.openDevice(device);
  } catch (IOException e) {
   e.printStackTrace();
  }
  EthernetPacket ether = new EthernetPacket();
  //設定自定義協議型別
  int type = Integer.decode("0x7799");
  ether.frametype = (short)type;
  byte[] desmac = stomac(macAddress);//目標mac地址
  byte[] srcmac = null;
  try {
   srcmac = stomac(getLocalMac(InetAddress.getLocalHost()));
  } catch (SocketException e) {
   e.printStackTrace();
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } // 本機MAC陣列
  ether.src_mac = srcmac;
  ether.dst_mac = desmac;
  udp.datalink = ether;
  //設定位元組的資料以及長度
   byte[] data = new byte[54];
      String typeStr = "hello";
         byte[] types = ByteUtil.ToByte(typeStr);
         for (int i = 0; i < 2; i++) {
         data[i] = types[i];
         }
   udp.data = data;
   sender.sendPacket(udp);