发送数据包
虽然名称WinPcap清楚地表明图书馆的目的是分组捕获,但还提供了其他有用的原始网络功能。其中,用户可以找到一组完整的功能来发送数据包。
请注意,原来的libpcap库目前没有提供任何方式发送数据包,因此这里显示的所有功能都是WinPcap扩展,在Unix下不起作用。
用pcap_sendpacket()发送单个数据包
发送数据包的最简单方式如下面的代码段所示。打开适配器后,调用pcap_sendpacket()发送手工制作的数据包。pcap_sendpacket()将包含要发送的数据的缓冲区的长度和要发送的缓冲区的适配器作为参数。请注意,缓冲区按原样发送到网络,无需任何操作。这意味着应用程序必须创建正确的协议头以发送有意义的东西。
#include <stdlib.h>
#include <stdio.h>
#include <pcap.h>
void main(int argc, char **argv)
{
pcap_t *fp;
char errbuf[PCAP_ERRBUF_SIZE];
u_char packet[100];
int i;
/* Check the validity of the command line */
if (argc != 2)
{
printf("usage: %s interface (e.g. 'rpcap://eth0')", argv[0]);
return;
}
/* Open the output device */
if ( (fp= pcap_open(argv[1], // name of the device
100, // portion of the packet to capture (only the first 100 bytes)
PCAP_OPENFLAG_PROMISCUOUS, // promiscuous mode
1000, // read timeout
NULL, // authentication on the remote machine
errbuf // error buffer
) ) == NULL)
{
fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n", argv