PF_PACKET을 이용하여 C코드로 패킷을 보내는 예

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/ethernet.h>
#include <netpacket/packet.h>

int main() {
    int sock_fd;
    struct sockaddr_ll dest_addr;
    char buffer(ETH_FRAME_LEN);
    unsigned char dest_mac(6) = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; // Broadcast address

    // Create a PF_PACKET socket
    sock_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
    if (sock_fd < 0) {
        perror("socket");
        return 1;
    }

    // Set the destination address for the socket
    memset(&dest_addr, 0, sizeof(dest_addr));
    dest_addr.sll_family = AF_PACKET;
    dest_addr.sll_ifindex = if_nametoindex("eth0"); // Change this to the interface you want to use
    dest_addr.sll_halen = ETH_ALEN;
    memcpy(dest_addr.sll_addr, dest_mac, ETH_ALEN);

    // Fill the buffer with the packet data
    memset(buffer, 0, sizeof(buffer));
    struct ethhdr *eth = (struct ethhdr *) buffer;
    memcpy(eth->h_dest, dest_mac, ETH_ALEN);
    eth->h_proto = htons(ETH_P_IP); // Change this to the protocol you want to use

    // Send the packet
    if (sendto(sock_fd, buffer, sizeof(buffer), 0, (struct sockaddr *) &dest_addr, sizeof(dest_addr)) < 0) {
        perror("sendto");
        return 1;
    }

    close(sock_fd);
    return 0;
}

이 예제 코드는 eth0 인터페이스를 활성화하고 패킷을 브로드캐스트 주소로 보내도록 설정했습니다. 필요에 따라 인터페이스 이름과 대상 MAC 주소를 변경할 수 있습니다. 패킷 데이터를 채우고 전송하는 방법도 프로토콜에 따라 변경해야 합니다.