winpcap发送单个数据包的示例

#define WIN32
#define HAVE_REMOTE
 
#include 
#include "pcap.h"
#include "Win32-Extensions.h"
 
//第一次遇到,在变量声明的时候不是随时都可以的,vs2010下 要把变量声明放到最前面,否则会报错
void genPacket(unsigned char *buf,int len)
{
       int i=0;
       //设置目标MAC地址为:01:01:01:01:01
       for (i=0;i<6;i++)
       {
           buf[i]=0x01;
       }
       //设置源MAC地址为:02:02:02:02:02
       for (i=6;i<12;i++)
       {
           buf[i]=0x02;
       }
       //设置协议标识为xc0xd,无任何实际意义
       buf[12]=0xc;
       buf[13]=0xd; 
       //填充数据包的内容 
       for(i=14;inext)
    {
        printf("%d. %s", ++i, d->name);
        if (d->description)
            printf(" (%s)\n", d->description);
        else
            printf(" (No description available)\n");
    }
   
    if(i==0)
    {
        printf("\nNo interfaces found! Make sureWinPcap is installed.\n");
        return -1;
    }
 
   
    printf("Enter the interface number (1-%d):",i);
    scanf("%d", &inum);
   
    if(inum < 1 || inum > i)
    {
        printf("\nInterface number out of range.\n");
       
        pcap_freealldevs(alldevs);
        return -1;
    }
   
   
    for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
   
   
if ( (adhandle= pcap_open(d->name, 65536,PCAP_OPENFLAG_PROMISCUOUS, 1000, NULL,errbuf) )== NULL)
    {
        fprintf(stderr,"\nUnable to open the adapter.%s is not supported by WinPcap\n", d->name);
       
        pcap_freealldevs(alldevs);
        return -1;
    }
 
   
    printf("\nlistening on %s...\n", d->description);
   
 
   
       

//获得生成的数据包,长度为MaxPacketLen
    genPacket(pBuf,MaxPacketLen);
 
    if ( (ret=pcap_sendpacket(adhandle,pBuf,MaxPacketLen)==-1)
    {
       printf("发送失败\n");
       pcap_close(adhandle);
        pcap_freealldevs(alldevs);
        return -1;
    }
 
 
     
     free(pBuf);
     pcap_close(adhandle);
     pcap_freealldevs(alldevs);
   
    return 0;
}

结果:



你可能感兴趣的:(wireshark/pcap)