- Tutorials
- API Examples
- User Guide
- Ch 1 - The Basics
- Ch 2 - libpcap
- 2.1 - The Main libpcap API Overview
- 2.2 - Getting a List of Interfaces
- 2.3 - Opening a Network Interface for Capture
- 2.4 - Opening offline capture
- 2.5 - Setting a packet filter
- 2.6 - Reading one packet at a time
- 2.7 - Reading multiple packets with dispatch loops
- 2.8 - Dumping captured packet to an offline file
- 2.9 - Transmitting packets
- 2.10 - Close Pcap and PcapDumper handles
- Ch 3 - Packet Decoding
- Ch 4 - Internals
- Ch 5 - Protocols
- Ch 6 - Native API
This example sends a packet using a network interface, one at a time. The packet is bogus, but none the less it will be sent as it uses the data link layer, a low level layer that expects the programmer to create the entire packets from scratch including the data link layer (i.e. the ethernet header.)
Download source from SVN: Packet Send Example
package org.jnetpcap.examples;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.jnetpcap.Pcap;
import org.jnetpcap.PcapIf;
public class PcapSendPacketExample {
public static void main(String[] args) {
List<PcapIf> alldevs = new ArrayList<PcapIf>(); // Will be filled with NICs
StringBuilder errbuf = new StringBuilder(); // For any error msgs
/***************************************************************************
* First get a list of devices on this system
**************************************************************************/
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;
}
PcapIf device = alldevs.get(0); // We know we have atleast 1 device
/*****************************************
* Second we open a network interface
*****************************************/
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);
/*******************************************************
* Third we create our crude packet we will transmit out
* This creates a broadcast packet
*******************************************************/
byte[] a = new byte[14];
Arrays.fill(a, (byte) 0xff);
ByteBuffer b = ByteBuffer.wrap(a);
/*******************************************************
* Fourth We send our packet off using open device
*******************************************************/
if (pcap.sendPacket(b) != Pcap.OK) {
System.err.println(pcap.getErr());
}
/********************************************************
* Lastly we close
********************************************************/
pcap.close();
}
}
»
Printer-friendly- Login or register to post comments
Send via Email
PDF Convert