Search code examples
c++cwindowsnetwork-programmingpcap

How to Send/Inject Packet with WinPcap


I'm working on Windows 10 64-bit and compiling with MinGW-w64, also using WinPcap.

Trying to send/inject packets like this:

#include <stdio.h>
#include <pcap.h>

int main(int argc, char **argv)
{
    char errbuf[PCAP_ERRBUF_SIZE];

    pcap_t *cap = pcap_open(argv[1], 65535, 0, 1000, 0, errbuf);
    printf("interface capture: %s\n", cap == 0 ? "failed" : "success");

    unsigned char packet[100];

    // Dst MAC
    packet[0] = 0x74;
    packet[1] = 0xc6;
    packet[2] = 0x3b;
    packet[3] = 0x00;
    packet[0] = 0x06;
    packet[5] = 0xb5;

    // Src MAC
    packet[6] = 0x74;
    packet[7] = 0xc6;
    packet[8] = 0x3b;
    packet[9] = 0x00;
    packet[10] = 0x06;
    packet[11] = 0xb5;

    // others
    for (unsigned char i = 12; i < 100; i++)
    {
        packet[i] = i;
    }

    printf("inject packet: %s\n", pcap_sendpacket(cap, packet, 100) == 0 ? "success" : "failed");
    return 0;
}

Everything looks fine and getting success on send/inject program.

However I'm not able to capture any packet, checked with Wireshark, still no luck.

I'm running program as administrator with CMD, also tried to send raw UDP packet.

Am I missing something or is this the proper way to send/inject packets into network interface?


Solution

  • I solved my problem! It was because of loopback on Windows.

    Please read Wireshark wiki page here: CaptureSetup/Loopback

    Installed Npcap which has loopback packet capture and injection support.

    For my case, simply captured packets from loopback network interface (provided by Npcap driver) and injected packets back to this loopback network interface again. Now I'm able to capture the packet in Wireshark and UDP receiver socket reads my injected packet successfully.