public static void main(String args[]) throws Exception {
    // chapter 2.2-4
    // initiate packet capture device
    final int snaplen = Pcap.DEFAULT_SNAPLEN;
    final int flags = Pcap.MODE_PROMISCUOUS;
    final int timeout = Pcap.DEFAULT_TIMEOUT;
    final StringBuilder errbuf = new StringBuilder();
    Pcap pcap = Pcap.openLive(args[0], snaplen, flags, timeout, errbuf);
    if (pcap == null) {
      System.out.println("Error while opening device for capture: " + errbuf.toString());
      return;
    }

    // Get local address
    e = NetworkInterface.getNetworkInterfaces();
    while (e.hasMoreElements()) {
      n = (NetworkInterface) e.nextElement();
      if (args[0].equals(n.getDisplayName())) {
        ee = n.getInetAddresses();
        mymac = n.getHardwareAddress();
        while (ee.hasMoreElements()) {
          inet = (InetAddress) ee.nextElement();
          System.out.println(n.getDisplayName() + " " + inet);
        }
      }
    }
    // Get IPv4 manually instead of looping through all IP's
    // myinet = inet.getAddress();

    // packet handler for packet capture
    pcap.loop(Integer.parseInt(args[1]), pcappackethandler, "pressure");
    pcap.close();
  }
Beispiel #2
0
  public static void main(String[] args) throws InterruptedException {
    SynthManager s = new SynthManager();
    s.start();

    List<PcapIf> alldevs = new ArrayList<PcapIf>(); // Will be filled with NICs
    StringBuilder errbuf = new StringBuilder(); // For any error msgs

    int r = Pcap.findAllDevs(alldevs, errbuf);
    if (r == Pcap.NOT_OK || alldevs.isEmpty()) {
      System.err.printf("Can't read list of devices, error is %s", errbuf.toString());
      return;
    }

    System.out.println("Network devices found:");

    int i = 0;
    for (PcapIf device : alldevs) {
      String description =
          (device.getDescription() != null) ? device.getDescription() : "No description available";
      System.out.printf("#%d: %s [%s]\n", i++, device.getName(), description);
    }

    System.out.print("\nPlease choose one of the above (only the number): ");
    Scanner scan = new Scanner(System.in);
    int deviceNum = scan.nextInt();

    PcapIf device = alldevs.get(deviceNum); // We know we have atleast 1 device
    System.out.printf(
        "\nChoosing '%s':\n",
        (device.getDescription() != null) ? device.getDescription() : device.getName());

    int snaplen = 64 * 1024; // Capture all packets, no trucation
    int flags = Pcap.MODE_PROMISCUOUS; // capture all packets
    int timeout = 10 * 1000; // 10 seconds in millis
    Pcap pcap = Pcap.openLive(device.getName(), snaplen, flags, timeout, errbuf);

    if (pcap == null) {
      System.err.printf("Error while opening device for capture: " + errbuf.toString());
      return;
    }

    PcapPacketHandler<String> jpacketHandler =
        new PcapPacketHandler<String>() {

          public void nextPacket(PcapPacket packet, String user) {

            try {
              byte[] sourceIp = packet.getHeader(new Ip4()).source();
              s.playSound(new int[] {sourceIp[0], sourceIp[1], sourceIp[2], sourceIp[3]});
            } catch (NullPointerException e) {

            }
          }
        };

    pcap.loop(-1, jpacketHandler, "");

    pcap.close();
  }
Beispiel #3
0
  /**
   * Ask use if they would like a dump file, if so, create one.
   *
   * @param pcap Reference to the PcapHandle.
   */
  @Override
  protected boolean beforeStart(Pcap pcap) {
    super.beforeStart(pcap);
    int option = JOptionPane.showConfirmDialog(GrassMarlin.window, "Create a dumpfile?");
    if (option == JOptionPane.OK_OPTION) {
      try {

        String filename = System.currentTimeMillis() + "_dump.pcap";
        File f = new File(Environment.DIR_LIVE_CAPTURE.getPath() + File.separator + filename);

        JFileChooser fc = new JFileChooser();
        fc.setSelectedFile(f);

        int i = fc.showSaveDialog(GrassMarlin.window.getContentPane());

        if (i == JFileChooser.APPROVE_OPTION) {
          dumper = pcap.dumpOpen(fc.getSelectedFile().getCanonicalPath());
        }

      } catch (Exception ex) {
        Logger.getLogger(LivePCAPImport.class.getName())
            .log(Level.SEVERE, "Failed to set dumpfile.", ex);
      }
    } else if (option == JOptionPane.CANCEL_OPTION) {
      return false;
    }
    isUsingDumpFile = dumper != null;
    return true;
  }
  public static void main(String[] args) {
    /*  ipaddress.add("139.130.4.5");
            ipaddress.add("74.125.226.22");
            ipaddress.add("69.171.230.68");
    */

    final StringBuilder errbuf = new StringBuilder();
    final Pcap pcap = Pcap.openOffline(FILENAME, errbuf);
    if (pcap == null) {
      System.err.println(errbuf);
      return;
    }
    pcap.loop(
        Pcap.LOOP_INFINITE,
        new JPacketHandler<StringBuilder>() {

          final Tcp tcp = new Tcp();

          final Ip4 ip4 = new Ip4();
          final Http http = new Http();

          public void nextPacket(JPacket packet, StringBuilder errbuf) {

            if (packet.hasHeader(Tcp.ID)) {
              if (packet.hasHeader(tcp) && packet.hasHeader(http)) {

                packet.getHeader(ip4);
                byte[] sip = new byte[4];
                sip = packet.getHeader(ip4).source();
                byte[] dip = new byte[4];
                dip = packet.getHeader(ip4).destination();
                String destinationip = org.jnetpcap.packet.format.FormatUtils.ip(dip);
                if (!(ipaddress.contains(destinationip))) {
                  ipaddress.add(destinationip);
                }
              }
            }
          }
        },
        errbuf);
    ipaddresscollection();
    //   pcap.close();

  }
Beispiel #5
0
  /**
   * We ignore the argument and open the {@link #device#getName() } instead.
   *
   * @param pathOrDevice Argument ignored.
   * @return Pcap handle to the NIC/device that belongs to this ImportItem.
   */
  @Override
  protected Pcap getHandle(String pathOrDevice) {
    Pcap handle = null;

    int snaplen = getImporter().getPreferences().snaplen;
    int mode = getImporter().getPreferences().mode;
    int timeout = getImporter().getPreferences().timeout;

    try {
      handle = Pcap.openLive(device.getName(), snaplen, mode, timeout, errorBuffer);
    } catch (UnsatisfiedLinkError err) {
      Logger.getLogger(PCAPImport.class.getName())
          .log(Level.SEVERE, "Importing PCAP is disabled.", err);
    }

    return handle;
  }
 /**
  * @param descriptor the protocol descriptor
  * @param listener the packet listener
  * @param file the dump file
  * @throws IOException if any error occur while reading the file
  */
 public FileProtocolParser(ProtocolDescriptor descriptor, PacketListener listener, File file)
     throws IOException {
   super(descriptor, listener, Pcap.openOffline(file.getAbsolutePath(), new StringBuilder()));
 }
 public synchronized void sendPacket(JBuffer paketToBeSended) {
   if (pcap.sendPacket(paketToBeSended) != Pcap.OK) {
     System.err.println(pcap.getErr());
   }
 }
  public void create() {

    /**
     * ************************************************************************* First we setup
     * error buffer and name for our file
     * ************************************************************************
     */
    final StringBuilder errbuf = new StringBuilder(); // For any error msgs

    final String file = "captured.txt";
    final String pcapFile = "captured.pcap";

    // delete the old txt file by opening it as an output

    try {
      FileWriter results = new FileWriter(file);
      // Create new File.
      BufferedWriter out = new BufferedWriter(results);

      out.close();
    } catch (IOException e) {
      System.out.println("The file cannot be opened " + e);
    }

    //

    System.out.println("Opening file for reading:" + pcapFile);
    /**
     * ************************************************************************* Second we open up
     * the selected file using openOffline call
     * ************************************************************************
     */
    Pcap pcap = Pcap.openOffline(pcapFile, errbuf);

    if (pcap == null) {
      System.err.printf("Error while opening device for capture: " + errbuf.toString());
      return;
    }

    /**
     * ************************************************************************* Third we create a
     * packet handler which will receive packets from the libpcap loop.
     * ************************************************************************
     */
    PcapPacketHandler<String> jpacketHandler =
        new PcapPacketHandler<String>() {

          public void nextPacket(PcapPacket packet, String user) {

            Tcp tcp = new Tcp();
            Ip4 ip = new Ip4();
            Udp udp = new Udp();

            final Http http = new Http();

            int TotalSize = 0;
            int caplen = 0;
            int ext = 0;
            int ack = 0;
            int istcp = 0;
            int ishttp = 0;
            int isudp = 0;
            int headerLength = 0;
            int PayloadLength = 0;

            // System.out.println(packet.getTotalSize());//costas
            // System.out.printf( " total size %-6d caplen= %6d  %6d  ",
            // packet.getTotalSize(),
            // packet.getCaptureHeader().caplen(),packet.getTotalSize()-
            // packet.getCaptureHeader().caplen());//costas

            TotalSize = packet.getTotalSize();
            caplen = packet.getCaptureHeader().caplen();

            PayloadLength = 0;
            headerLength = 0;

            ext = 0;
            ack = 0;
            // ****************************************************
            String ssourceIp = "";
            String destinIp = "";
            String sourceIp = "";
            if (packet.hasHeader(ip)) {
              sourceIp = FormatUtils.ip(ip.source());
              destinIp = FormatUtils.ip(ip.destination());
            }

            if (packet.hasHeader(udp)) // for udp packets
            {
              isudp = 1;
              headerLength = udp.getHeaderLength();
              if (packet.hasHeader(ip)) // check for the existance of ip
              {

                InetAddress ipAddress = null;

                try {
                  ipAddress = InetAddress.getByAddress(ip.source()); // get
                  // the
                  // ip
                  // address
                  // ipAddress=
                  // InetAddress.getByAddress(ip.destination());
                } catch (UnknownHostException e) {
                }

                ssourceIp = ipAddress.getHostAddress(); // get the ip
                // address

                if (sourceIp.startsWith("10.3.")
                    || sourceIp.startsWith("192.168.")
                    || sourceIp.startsWith("10.239.")
                    || sourceIp.startsWith("10.4.")) {
                  ext = 0; // out-going message
                } else {
                  ext = 1; // in-coming message
                }

                ack = 0;
              } // end for header ip

              PayloadLength = udp.getPayloadLength();

            } // end for udp packet.
            else {
              isudp = 0;
            }

            // *******************************************************************

            if (packet.hasHeader(http)) {
              ishttp = 1;
              PayloadLength = http.getPayloadLength();
              if (packet.hasHeader(ip)) //
              {

                InetAddress ipAddress = null;
                try {
                  ipAddress = InetAddress.getByAddress(ip.source());
                } catch (UnknownHostException e) {
                }

                ssourceIp = ipAddress.getHostAddress(); // get the ip
                // address

                if (sourceIp.startsWith("10.3.")
                    || sourceIp.startsWith("192.168.")
                    || sourceIp.startsWith("10.239.")
                    || sourceIp.startsWith("10.4.")) {
                  ext = 0; // internal address
                } else {
                  ext = 1; // external
                }
              } // end for header ip
            } else // not http
            {
              ishttp = 0;
            } // end for http

            // **********************************************
            if (packet.hasHeader(tcp)) {
              istcp = 1;
              headerLength = tcp.getHeaderLength();
              if (packet.hasHeader(ip)) // check for existance of ip
              // header
              {

                InetAddress ipAddress = null;
                try {
                  ipAddress = InetAddress.getByAddress(ip.source());
                } catch (UnknownHostException e) {
                }

                ssourceIp = ipAddress.getHostAddress(); // get the ip
                // address

                if (sourceIp.startsWith("10.3.")
                    || sourceIp.startsWith("192.168.")
                    || sourceIp.startsWith("10.239.")
                    || sourceIp.startsWith("10.4.")) {

                  ext = 0; // out-going message
                } else {

                  ext = 1; // in-coming message
                }

                if (tcp.flags_ACK() == true) ack = 1;
                else ack = 0;
              } // end for header ip

              PayloadLength = tcp.getPayloadLength();

            } // end for tcp packet.
            else {
              istcp = 0;
            }

            String rec =
                istcp
                    + ","
                    + ishttp
                    + ","
                    + isudp
                    + ","
                    + ack
                    + ","
                    + ext
                    + ","
                    + TotalSize
                    + ","
                    + PayloadLength
                    + ","
                    + caplen
                    + ","
                    + headerLength
                    + ","
                    + sourceIp
                    + ","
                    + destinIp
                    + ","
                    + user;
            write_rec(file, rec); // write raw data in a text file.
          }
        };

    // capturing all the packets of the Pcap file
    try {
      pcap.loop(Pcap.LOOP_INFINITE, jpacketHandler, "?");
    } finally {

      // Last thing to do is close the pcap handle
      pcap.close();
      System.out.println("End of packet capturing..Pcap file closed");
      System.out.println("Now the analyser is running...");
      scanTxtFile(file, "test-final.arff"); // scans the file.txt and
      // creates a weka file
      // (arff)
    }
  } // end of main