#include <stdio.h> #include <winsock2.h> #include <Windows.h> #include <pcap.h>
#pragma comment(lib, "packet.lib") #pragma comment(lib, "wpcap.lib") #pragma comment(lib,"WS2_32.lib")
#define ETH_ARP 0x0806 #define ARP_HARDWARE 1 #define ETH_IP 0x0800 #define ARP_REQUEST 1 #define ARP_RESPONSE 2
struct EthernetHeader { u_char DestMAC[6]; u_char SourMAC[6]; u_short EthType; };
struct ArpHeader { unsigned short hdType; unsigned short proType; unsigned char hdSize; unsigned char proSize; unsigned short op; u_char smac[6]; u_char sip[4]; u_char dmac[6]; u_char dip[4]; };
struct ArpPacket { EthernetHeader ed; ArpHeader ah; };
pcap_t * OpenPcap(int nChoose) { pcap_t *pcap_handle; pcap_if_t *alldevs; char errbuf[PCAP_ERRBUF_SIZE];
if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1) exit(0); for (int x = 0; x < nChoose - 1; ++x) alldevs = alldevs->next;
if ((pcap_handle = pcap_open(alldevs->name, 65536, PCAP_OPENFLAG_PROMISCUOUS, 1000, NULL, errbuf )) == NULL) { pcap_freealldevs(alldevs); exit(0); } return pcap_handle; }
int main(int argc, char *argv[]) { pcap_t *handle; EthernetHeader eh; ArpHeader ah;
unsigned char sendbuf[42]; unsigned char src_mac[6] = { 0xaa, 0xaa, 0xaa, 0xaa, 0xff, 0xff }; unsigned char src_ip[4] = { 0x01, 0x02, 0x03, 0x04 };
handle = OpenPcap(3);
memset(eh.DestMAC, 0xff, 6); memcpy(eh.SourMAC, src_mac, 6); memcpy(ah.smac, src_mac, 6); memset(ah.dmac, 0xff, 6); memcpy(ah.sip, src_ip, 4); memset(ah.dip, 0x05, 4);
eh.EthType = htons(ETH_ARP); ah.hdType = htons(ARP_HARDWARE); ah.proType = htons(ETH_IP); ah.hdSize = 6; ah.proSize = 4; ah.op = htons(ARP_REQUEST);
memset(sendbuf, 0, sizeof(sendbuf)); memcpy(sendbuf, &eh, sizeof(eh)); memcpy(sendbuf + sizeof(eh), &ah, sizeof(ah));
if (pcap_sendpacket(handle, sendbuf, 42) == 0) { printf("发送ARP数据包成功! \n"); }
system("pause"); return 0; }
|