我正在尝试创建一个程序,这样每当我从特定MAC地址接收到一个接口的数据包时,我想传输另一个数据包(pcap文件中包含的回复数据包)。下面的程序部分有效。它有两个问题。
无法实现同步,即每当我收到时都进行传输。
此外,由于某些未知原因,尽管重播pcap文件我想用作对我收到的每个数据包的响应,包含65000个数据包,但只传输了800个(再次未同步),程序终止时没有错误。 ..
有什么想法?谢谢!
#include <time.h>
#include <pcap.h>
#include <libnet.h>
#include <signal.h>
#include <sys/wait.h>
#include <inttypes.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/ethernet.h>
#include <netpacket/packet.h>
#include <netinet/if_ether.h>
int make_raw_sock(const char *interface, struct sockaddr_ll *sa);
int main(int argc, char *argv[])
{
const char *srcmac;
char mac[]={0x28,0x63,0x36,0x91,0x3c,0x0e};
//SET UP FOR INJECTING SOCKET
//Buffer to send data.
char buf[1514];
struct sockaddr_ll sa;
const u_char *packetstored;
const u_char *packetrx;
struct pcap_pkthdr headerst;
struct pcap_pkthdr headerrx;
pcap_t *mypcapfile;
pcap_t *p;
//Create the socket for injection.
int ps = 0;
ps = make_raw_sock("lo", &sa);
if (ps<0)
{
fprintf(stderr,"Failure in socket creation\n");
exit(-1);
}
//PARAMETERS FOR LIBPCAP
//The maximum number of packets to be captured.
//uint32_t count = 250000;
//The snapshot lenght.
uint32_t snaplen = 1514;
//Buffer for errors.
char errbuf[PCAP_ERRBUF_SIZE];
//Set interface in promiscuous mode.
int promisc = 1;
//timeout, in milliseconds.
int to_ms = 1000;
fprintf(stdout,"Parent process id = %d\n",getpid());
if (!(p = pcap_open_live("lo", snaplen, promisc, to_ms, errbuf)))
{
fprintf(stderr, "Error opening interface %s: %s\n","lo", errbuf);
exit(EXIT_FAILURE);
}
mypcapfile = pcap_open_offline("replay3.pcap", errbuf);
if (mypcapfile == NULL)
{
printf("Error pcap_open_offline(): %s\n", errbuf);
exit(EXIT_FAILURE);
}
int counter;
while (1)
{
packetrx = pcap_next(p, &headerrx);
srcmac = packetrx;
if (packetrx == NULL)
{
break;
}
else
{
if (!strncmp(srcmac,mac,6))
{
packetstored = pcap_next(mypcapfile, &headerst);
memcpy(buf,packetstored,headerst.caplen);
sendto(ps, buf, headerst.caplen, 0, (struct sockaddr*)&sa, sizeof(sa));
counter = counter + 1;
}
}
}
fprintf(stdout,"Packets sent:%d\n",counter);
return (0);
}
int make_raw_sock(const char *interface, struct sockaddr_ll *sa)
{
int ps;
struct ifreq ifr;
ps = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (ps < 0)
{
return ps;
}
strcpy(ifr.ifr_name, interface);
if (ioctl(ps, SIOCGIFINDEX, &ifr) != 0)
{
close(ps);
return -1;
}
memset(sa, 0, sizeof(*sa));
sa->sll_family = AF_PACKET;
sa->sll_ifindex = ifr.ifr_ifindex;
sa->sll_halen = sizeof(struct ether_addr);
return ps;
}